/**
 * Created by 王涛 on 2017/6/8.
 */
$(function () {
    alert(123);
    $('#side-menu li.addFirstCase').addClass('active');//更改导航列表选中样式
    // 以下为页面公共方法  start
    //confirm 弹窗  start
    function confirmModel(title, body, okBtn, cancelBtn, okHidden) {
        if (!title) {
            title = '温馨提示';
        }
        if (!body) {
            body = '确定要删除吗？';
        }
        if (!okBtn) {
            okBtn = '确定';
        }
        if (!cancelBtn) {
            cancelBtn = '取消';
        }
        $.confirm({
            title: title,
            body: body,
            okBtn: okBtn,
            cancelBtn: cancelBtn,
            transition: true,
            okHidden: function () {
                okHidden();
            }
        });
    } //confirm 弹窗  end

    //alert 弹窗  start
    function alertModel(title, body) {
        if (!title) {
            title = '温馨提示';
        }
        if (!body) {
            body = '出错了，再来一次！';
        }
        $.alert({
            title: title,
            body: body,
            transition: true
        });
    } //alert 弹窗  end

    //保存下一步  切换标签页方法  start
    function saveNext() {

        var actived = $('#addCaseNavTabs').find('li.active');
        actived.removeClass('active');
        // 川  定义self,用于保存当前li的下一个 ⬇️；
        var self;
        // 川  定义self,用于保存当前li的下一个 ⬆️；

        if (actived.next().find('a').hasClass('disabled')) {
            self = actived.next().next();
            actived.next().next().addClass('active');
            var id = actived.next().next().find('a').attr('href');
            $(id).addClass('active').prev().prev().removeClass('active');
        } else {
            self = actived.next();
            actived.next().addClass('active');
            var id = actived.next().find('a').attr('href');
            $(id).addClass('active').prev().removeClass('active');
        }
        scrollTo(0, 0);

        // 川 ⬇️

        var isSave = self.attr('data-save');
        var isLoad = self.attr('data-load');
        var tabPage = self.attr('data-href');
        if ((isLoad === 'no') && (isSave === 'yes')) {
            beforeGetData(tabPage);
        }
        // 川 ⬆️

//之前的操作，暂时注释；
        // beforeGetData(actived.next().attr('data-href'));

    } //保存下一步  切换标签页方法  end

    //主要症状列表  数据  start
    var MainSymptomsList = [];
    var MainSymptomsStr = '';

    var MainthyHBList = {};

    function strAdd(selected, data, addId) {
        var MainthyHBsStr = '';
        MainSymptomsStr = "";
        var thyHBarr = [];
        var ArrEach = [];
        if (addId.indexOf('thyHB') >= 0) {
            if (addId == "thyHB1") {
                ArrEach = MainthyHBList.thyroid.symptoms;
            } else if (addId == "thyHB2") {
                ArrEach = MainthyHBList.thyroid.examination
            } else if (addId == "thyHB3") {
                ArrEach = MainthyHBList.thyroid.hyperthyroidism
            } else if (addId == "thyHB4") {
                ArrEach = MainthyHBList.adrenal.symptoms
            } else if (addId == "thyHB5") {
                ArrEach = MainthyHBList.adrenal.accompanied_symptom
            }
            $.each(ArrEach, function (k, v) {
                MainthyHBsStr += '<div class="lable-item"><label><input type="checkbox" value="' + v.value + '" checked="checked" id="' + v.id + '">' + v.value + '</label></div>'
            });
            $('#addSymptom .modal-body').html('<div class="addModel-group"><h4>常见症状</h4>' + MainthyHBsStr + '</div>');
        } else {
            for (var i = 0; i < MainSymptomsList.length; i++) {
                // MainSymptomsStr='';
                MainSymptomsStr += '<div class="addModel-group">' +
                    '<h4>' + MainSymptomsList[i].title + '</h4>';
                if(MainSymptomsList[i].data){
                    for (var s = 0; s < MainSymptomsList[i].data.length; s++) {
                        MainSymptomsStr += '<div class="lable-item"><label>' +
                            '<input type="checkbox" value="' + MainSymptomsList[i].data[s].name + '" checked="checked" id="symptomName_' + MainSymptomsList[i].data[s].id + '">' + MainSymptomsList[i].data[s].name + '</label></div>';
                    }
                }
                MainSymptomsStr += '</div>';
            }
            $('#addSymptom .modal-body').html(MainSymptomsStr);
        }
        if (selected) {
            for (var s = 0; s < selected.length; s++) {
                $('#addSymptom .modal-body').find('input[value="' + selected[s].name + '"]').parent().parent().addClass('current');
            }
        }


    };

    function getMainSymptoms(selected, addId) {
        var getUrl = '';
        if (addId.indexOf('thyHB') >= 0) {
            getUrl = '/manage/hpi/symptoms/items';
            if (JSON.stringify(MainthyHBList) !== '{}') {
                strAdd(selected, MainthyHBList, addId)
            } else {
                $.get(getUrl, function (data) {
                    if (data.code === 10000) {
                        MainthyHBList = data.data;
                        strAdd(selected, MainthyHBList, addId)
                    } else if (data.code === 40100) {
                        aClick();
                    } else {
                        alertModel('', data.message);
                    }

                })
            }

        } else {
            getUrl = '/manage/symptom/list';
            if (MainSymptomsList.length > 0) {
                strAdd(selected, MainSymptomsList, addId)
            } else {
                $.get(getUrl, function (data) {
                    if (data.code === 10000) {
                        MainSymptomsList = data.data;
                        strAdd(selected, MainSymptomsList, addId);
                    } else if (data.code === 40100) {
                        aClick();
                    } else {
                        alertModel('', data.message);
                    }

                })

            }

        }


    }//主要症状列表  数据  end

    //主要症状弹出框 症状名字点击事件  start
    var selectedSymptomList = [];
    $('#addSymptom').delegate('div.lable-item input', 'click', function () {
        var divBox = $(this).parent().parent();
        if (divBox.hasClass('current')) {
            for (var i = 0; i < selectedSymptomList.length; i++) {
                if (selectedSymptomList[i].id == $(this).attr('id')) {
                    selectedSymptomList.splice(i, 1);
                }
            }
            divBox.removeClass('current');
        } else {
            if (selectedSymptomList.length >= 5) {
                $.alert({
                    title: '温馨提示',
                    body: '主要症状最多可选5个！',
                    transition: true,
                    okHidden: function () {
                        $('.sui-modal-backdrop.fade.in').removeClass('alertZindex');
                    }
                });
                $('.sui-modal-backdrop.fade.in').addClass('alertZindex');
            } else {
                selectedSymptomList.push({name: $(this).val(), id: $(this).attr('id')});
                divBox.addClass('current');
            }
        }
    });//主要症状弹出框 症状名字点击事件  end

    //主要症状弹出框 添加症状按钮点击事件  start
    $('#saveSymptom').click(function () {
        var id = $(this).attr('data-id');
        var str = '';
        for (var i = 0; i < selectedSymptomList.length; i++) {
            str += '<li class="tag-selected with-x" data-id="' + selectedSymptomList[i].id + '" data-name="' + selectedSymptomList[i].name + '"><input type="hidden" value="' + selectedSymptomList[i].name + '" name="symptom[]">' + selectedSymptomList[i].name + '<i>×</i></li>'
        }
        if (id.indexOf('thyHB') >= 0) {
            $("button." + id).parents("div.ibox").find('ul.sui-tag').html(str)
        } else {
            $('#' + id).find('ul.sui-tag').html(str);

        }
    });//主要症状弹出框 添加症状按钮点击事件  end

    //将表单serialize 获取的值转为对象 格式  start
    function formToJson(data) {
        data = data.replace(/&/g, "\",\"");
        data = data.replace(/=/g, "\":\"");
        data = "{\"" + data + "\"}";
        return data;
    }//将表单serialize 获取的值转为对象 格式  end

    //开始时间和结束时间判断方法  start
    function checkTwoDate(sTime, eTime) {
        var start_time = new Array();
        var end_time = new Array();
        if (sTime && eTime) {
            start_time = sTime.split('-');
            end_time = eTime.split('-');
            var start_day, end_day;
            if (start_time.length == 2) {
                start_day = '01';
            } else {
                start_day = start_time[2];
            }
            if (end_time.length == 2) {
                end_day = '01';
            } else {
                end_day = end_time[2];
            }
            var sdate = new Date(start_time[0], parseInt(start_time[1] - 1), start_day);
            var edate = new Date(end_time[0], parseInt(end_time[1] - 1), end_day);
            if (sdate > edate) {
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }//开始时间和结束时间判断方法  end

    //检测输入框  如果输入值  就必须是数字且大于0 start
    function checkIsNumber(arr) {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i]) {
                if (isNaN(arr[i])) {
                    return false;
                }
                if (arr[i] <= 0) {
                    return false;
                }
            }
        }
        return true;
    }//检测输入框  如果输入值  就必须是数字且大于0 end
    //检测血糖值 start
    function checkBloodNum(arr) {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i]) {
                if (isNaN(arr[i])) {
                    return false;
                }
                if (arr[i] <= 0 || arr[i] > 50) {
                    return false;
                }
            }
        }
        return true;
    }//检测血糖值 end

    // 页码函数方法  start
    function page(id, data, fun, param) {
        var totalPages = Math.ceil(data.pagination.total / data.pagination.per_page);
        $('#' + id).jqPaginator({
            totalPages: totalPages,
            visiblePages: 5,
            currentPage: data.pagination.current_page,
            first: '',
            last: '',
            onPageChange: function (e) {
                param.page = e;
                fun(param);
            }
        })
    }// 页码函数方法  end

    //标签页添加浏览器记住事件  start
    $('#addCaseNavTabs li').click(function () {
        if (!($(this).find('a').hasClass('disabled'))) {
            var id = $(this).find('a').attr('href');
            sessionStorage.setItem('tabPage', id);
        }
    });
    var tabPage = sessionStorage.getItem('tabPage');
    if (tabPage) {
        $(tabPage).addClass('active').siblings().removeClass('active');
        $('#addCaseNavTabs li').find('a[href="' + tabPage + '"]').parent().addClass('active').siblings().removeClass('active');
    }
    //标签页添加浏览器记住事件  end

    //保存成功！对当前标签添加标记  start
    function saveSeccessTab() {
        $('#addCaseNavTabs li.active').attr('data-save', 'yes');
    }

    //保存成功！对当前标签添加标记  end


    // 以上为页面公共方法  end


    // 页面加载 获取保存过的页面  start
    function getSavePage(recordId) {
        var result = {
            record_id: recordId,
            items: 'complaint,hpi,past,person,marriage,family,physical,auxiliary,diagnose,dispose'
        }
        $.get('/manage/record/items', result, function (data) {
            if (data.code === 10000) {
                $.each(data.data, function (i, v) {
                    if (v) {
                        $('#addCaseNavTabs li[data-href="' + i + '"]').attr('data-save', 'yes');
                    }
                });
                $('#addCaseNavTabs').attr('data-know', 'yes');
            } else if (data.code === 40100) {
                aClick();
            }
        });
    }// 页面加载 获取保存过的页面  end

    //患者基本信息 实例 start
    var baseMessage = new Yox({
        el: '#baseMessageForm',
        template: '#baseMessageComp',
        data: {
            baseMess: {
                name: '',
                phone: '',
                hospital_id: '',
                doctor_id: '',
                sex: '1',
                birthday: '',
                medical_number: '',
                clinic_at: nowData(),
                cardnumber: '',
                diabetes_type: '',
                // is_gestation:'1',
                special_illness: '',
                nation: '1',
                province: '0',
                city: '0',
                county: '0',
                record_id: '',
                patient_id: ''
            },
            saveUrl: '/manage/record/store',
            cityUrl: '/manage/address/cities',
            countyUrl: '/manage/address/counties',
            doctorUrl: '/manage/hospital/doctors'
        },
        methods: {
            saveMessage: function () {
                var birthdayVal = $('#birthday').val();
                var clinicAtVal = $('#clinicAt').val();
                if (checkDate(birthdayVal)) {
                    this.$context.baseMess.birthday = birthdayVal;  //将出生日期选择放入实例数据
                    // if(checkDate(clinicAtVal)){
                    this.$context.baseMess.clinic_at = clinicAtVal; //将就诊日期选择放入实例数据
                    if (this.$context.baseMess.name) {
                        if (checkPhone(this.$context.baseMess.phone)) {
                            this.$context.baseMess.hospital_id = $('#hospitalId').val();  //将医院选择放入实例数据
                            this.$context.baseMess.doctor_id = $('#doctorId').val();  //将医生选择放入实例数据
                            this.$context.baseMess.province = $('#province').val();  //将省份选择放入实例数据
                            this.$context.baseMess.city = $('#city').val();  //将城市选择放入实例数据
                            this.$context.baseMess.county = $('#county').val();  //将区县选择放入实例数据
                            var _this = this;
                            if (record_id) {
                                this.$context.saveUrl = '/manage/record/update';
                            }
                            var reg = /^([\u4E00-\uFA29]*[0-9]*[a-z]*[A-Z]*)+$/;
                            if ((reg.test((this.$context.baseMess.name).trim())) && (chkstrlen((this.$context.baseMess.name).trim()) <= 16)) {
                                var cardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;  // 15位或者18位身份证号正则
                                if ((!this.$context.baseMess.cardnumber) || ((this.$context.baseMess.cardnumber) && (cardReg.test(this.$context.baseMess.cardnumber)))) {
                                    ajaxPost(this.$context.saveUrl, this.$context.baseMess, function (data) {
                                        if (data.code == 10000) {
                                            alertModel('', '保存成功!');
                                            if (!record_id) {
                                                _this.$context.baseMess.record_id = data.data.record_id;
                                                _this.$context.baseMess.patient_id = data.data.patient_id;
                                                sessionStorage.setItem('record_id', data.data.record_id);//将病历id存入浏览器  页面刷新时候获取id请求病历数据
                                                sessionStorage.setItem('patient_id', data.data.patient_id);//将患者id存入浏览器  页面刷新时候获取id请求患者基本信息
                                                record_id = data.data.record_id;
                                                $('input#record_id').val(data.data.record_id);  //将病历id存入页面基本信息下隐藏输入框中
                                            }
                                        } else if (data.code === 40100) {
                                            aClick();
                                        } else {
                                            alertModel('', data.message);
                                        }
                                    }, function (x, t, e) {
                                        if (x.status != 422) {
                                            alertModel('', '保存失败，再来一次吧！');
                                        }
                                    })
                                } else {
                                    alertModel('', '身份证号输入不合法!');
                                }
                            } else {
                                alertModel('', '姓名长度不能超过16个字符!');
                            }
                        } else {
                            alertModel('', '请输入正确手机号!');
                        }
                    } else {
                        alertModel('', '请输入姓名!');
                    }
                    // }else{
                    //     $('.clinicAt').val('');
                    //     $('.clinicAt').attr('placeholder','请重新选择就诊日期');
                    //     alertModel('','请重新选择就诊日期!');
                    // }
                } else {
                    $('.birthday').val('');
                    $('.birthday').attr('placeholder', '请重新选择出生日期');
                    alertModel('', '请重新选择出生日期!');
                }

            },
            provinceChange: function () {
                if (this.$context.baseMess.province) {
                    $.get(this.$context.cityUrl, {province_id: this.$context.baseMess.province}, function (data) {
                        if (data.code === 10000) {
                            var str = '<option value="0">请选择</option>';
                            $.each(data.data, function (i, v) {
                                str += '<option value="' + v.id + '">' + v.name + '</option>'
                            });
                            $('#city').html(str);
                            baseMessage.$context.baseMess.city = $('#city').val();   //将第一个城市id放入实例数据
                            baseMessage.cityChange();                               //请求第一个 城市所对应的 区县
                        } else if (data.code === 40100) {
                            aClick();
                        } else {
                            alertModel('', data.message);
                        }
                    });
                } else {
                    this.$context.baseMess.city = '';
                    $('#city').html('<option value="0">请选择</option>');
                    this.$context.baseMess.county = '';
                    $('#county').html('<option value="0">请选择</option>');
                }
            },
            cityChange: function () {
                if (this.$context.baseMess.city) {
                    $.get(this.$context.countyUrl, {city_id: this.$context.baseMess.city}, function (data) {
                        if (data.code === 10000) {
                            var str = '<option value="0">请选择</option>';
                            $.each(data.data, function (i, v) {
                                str += '<option value="' + v.id + '">' + v.name + '</option>'
                            });
                            $('#county').html(str);
                            baseMessage.$context.baseMess.county = $('#county').val();   //将第一个区县id放入实例数据
                        } else if (data.code === 40100) {
                            aClick();
                        } else {
                            alertModel('', data.message);
                        }
                    });
                } else {
                    this.$context.baseMess.county = '';
                    $('#county').html('<option value="0">请选择</option>');
                }
            },
            hospitalChange: function (doctorId) {
                if (this.$context.baseMess.hospital_id !== "") {
                    $.get(this.$context.doctorUrl, {hospital_id: this.$context.baseMess.hospital_id}, function (data) {
                        if (data.code === 10000) {
                            var str = '';
                            $.each(data.data, function (i, v) {
                                if (doctorId && doctorId == v.id) {
                                    str += '<option value="' + v.id + '" selected>' + v.name + '</option>';
                                } else {
                                    str += '<option value="' + v.id + '">' + v.name + '</option>';
                                }
                            });
                            $('#doctorId').html(str);
                        } else if (data.code === 40100) {
                            aClick();
                        } else {
                            alertModel('', data.message);
                        }
                    });

                }
            }
        }
    });//患者基本信息 实例 end

    // $("#baseMessageForm").find("button").click(function(){
    //
    // });

    $('input.phoneLength').bind('input.phoneLength propertychange', function () {
        var reg = /^\d+$/;
        if (baseMessage.$context.baseMess.phone.length > 11) {
            var val = baseMessage.$context.baseMess.phone.slice(0, 11);
            baseMessage.$context.baseMess.phone = val;
            $(this).val($(this).val().slice(0, 11));
        } else {
            if (!(reg.test(baseMessage.$context.baseMess.phone))) {
                baseMessage.$context.baseMess.phone = (baseMessage.$context.baseMess.phone.slice(0, $(this).val().length - 1));
                $(this).val($(this).val().slice(0, $(this).val().length - 1));
            }
        }
    }); //手机号限制长度

    //页面刷新时候  根据浏览器sessionStorage存储的病历id获取患者基本信息  start
    var patient_id = sessionStorage.getItem('patient_id');//保存患者id值
    var record_id = sessionStorage.getItem('record_id');//保存病历id值

//已经创建的病例⬇️
    if (patient_id) {
        baseMessage.$context.baseMess.patient_id = patient_id;
        $.get('/manage/patient/edit', {patient_id: patient_id}, function (data) {
            $('#name').val(data.data.name);
            baseMessage.$context.baseMess.name = data.data.name;
            $('#phone').val(data.data.phone);
            baseMessage.$context.baseMess.phone = data.data.phone;
            //存储手机号  用于点处理保存跳转列表页  搜索
            sessionStorage.setItem('patientPhone', data.data.phone);
            if (data.data.hospital) {
                $('#hospitalId').val(data.data.hospital.key);
                baseMessage.$context.baseMess.hospital_id = data.data.hospital.key;
            } else {
                $("#hospitalId").val("")
            }
            if (data.data.doctor) {
                $('#doctorId').val(data.data.doctor.key);
                baseMessage.$context.baseMess.doctor_id = data.data.doctor.key;
                if (!($('li.nav-header strong.font-bold').attr('data-doctor'))) {
                    baseMessage.hospitalChange(data.data.doctor.key);
                }
            } else {
                $("#doctorId").val("")
            }

            //$('#is_gestation').val(data.data.is_gestation.key);
            //baseMessage.$context.baseMess.is_gestation=data.data.is_gestation.key;
            $('#sexSelect').val(data.data.sex.key);
            baseMessage.$context.baseMess.sex = data.data.sex.key;

            if (data.data.sex.key == 0) {
                $('#is_gestation').attr('disabled', 'disabled');
                // 如果是男性也可以点击tab月经婚育史⬇️
                $("#hunyushi").find("tr.manHide,td.manHide").hide();
                // $('#yjhysTab').addClass('disabled').attr('data-toggle', '');
                $('#baseMessageForm').find('select[name="is_gestation"]').val(0);
                baseMessage.$context.baseMess.is_gestation = 0;
            } else {
                $("#hunyushi").find("tr.manHide,td.manHide").show();
            }
            $('#birthday').val(data.data.birthday);
            $('#medical_number').val(data.data.medical_number);
            baseMessage.$context.baseMess.medical_number = data.data.medical_number;
            $('#clinicAt').val(data.data.first_visit);
            if (data.data.diabetes_type) {
                $('#diabetes_type').val(data.data.diabetes_type.key);
                baseMessage.$context.baseMess.diabetes_type = data.data.diabetes_type.key;
            }

            $('#cardnumber').val(data.data.cardnumber);
            baseMessage.$context.baseMess.cardnumber = data.data.cardnumber;
            if (data.data.special_illness) {
                $('#special_illness').val(data.data.special_illness.key);
                baseMessage.$context.baseMess.special_illness = data.data.special_illness.key;
            }
            if (data.data.nation) {
                $('#nation').val(data.data.nation.key);
                baseMessage.$context.baseMess.nation = data.data.nation.key;
            }

            $('#province').val(data.data.province);
            var cityId = data.data.city;
            var countyId = data.data.county;
            if (data.data.province) {
                $.get('/manage/address/cities', {province_id: data.data.province}, function (data) {
                    if (data.code === 10000) {
                        var str = '<option value="0">请选择</option>';
                        $.each(data.data, function (i, v) {
                            str += '<option value="' + v.id + '">' + v.name + '</option>'
                        });
                        $('#city').html(str);
                        $('#city').val(cityId);
                        baseMessage.$context.baseMess.city = $('#city').val();   //将第一个城市id放入实例数据
                        if (cityId) {
                            $.get('/manage/address/counties', {city_id: cityId}, function (data) {
                                if (data.code === 10000) {
                                    var str = '<option value="0">请选择</option>';
                                    $.each(data.data, function (i, v) {
                                        str += '<option value="' + v.id + '">' + v.name + '</option>'
                                    });
                                    $('#county').html(str);
                                    $('#county').val(countyId);
                                    baseMessage.$context.baseMess.county = $('#county').val();   //将第一个区县id放入实例数据
                                } else if (data.code === 40100) {
                                    aClick();
                                } else {
                                    alertModel('', data.message);
                                }
                            });                             //请求第一个 城市所对应的 区县
                        }
                    } else if (data.code === 40100) {
                        aClick();
                    } else {
                        alertModel('', data.message);
                    }
                });
            }
        });
    }
    if (record_id) {
        getSavePage(record_id);
        baseMessage.$context.baseMess.record_id = record_id;
        $('input#record_id').val(record_id);//将病历id存入页面基本信息下隐藏输入框中
        var timer = setInterval(function () {
            if ($('#addCaseNavTabs').attr('data-know')) {
                clearInterval(timer);
                if (($('#addCaseNavTabs li.active').attr('data-js')) == 'caseFirst') {
                    var tabPage = $('#addCaseNavTabs li.active').attr('data-href');
                    if ($('#addCaseNavTabs li.active').attr('data-save') == 'yes') {
                        beforeGetData(tabPage);
                    }
                }
            }
        }, 10);
    }
    //页面刷新时候  根据浏览器sessionStorage存储的病历id获取患者基本信息  end
    //页面刷新 或者 标签页点击  获取当前信息  start
    function beforeGetData(tabPage) {
        var url = '/manage/' + tabPage + '/edit';
        var result = {record_id: record_id};
        if (tabPage === 'hpi') {
            result = {record_id: record_id, include: 'sub'};
        }
        GetData(url, result, tabPage);


    }//页面刷新 或者 标签页点击  获取当前信息  end
    //获取数据 请求方法 封装函数  start
    function GetData(url, result, success) {
        $.get(url, result, function (data) {
            if (data.code === 10000) {
                $('#addCaseNavTabs li[data-href="' + success + '"]').attr('data-load', 'yes');
                if (success === 'complaint') {
                    complaint(data.data);
                } else if (success === 'hpi') {
                    hpi(data.data);
                } else if (success === 'past') {
                    past(data.data);
                } else if (success === 'person') {
                    person(data.data);
                } else if (success === 'marriage') {
                    marriage(data.data);
                } else if (success === 'family') {
                    family(data.data);
                }
            } else if (data.code === 40100) {
                aClick();
            } else {
                alertModel('', data.message);
            }
        })
    }//获取数据 请求方法 封装函数  end
    //主诉  处理数据方法  start
    function complaint(data) {
        // 川  ↓
        //放置用药史数据
        if (data.medication) {
            var medicationStr = '<table class="table-bordered table-striped table-hover text-center medicationList-table"><thead><tr><th>开始时间</th><th>结束时间</th><th>名称</th><th>剂量</th><th>单位</th><th>用法</th><th>频次</th><th>其他备注</th><th>操作</th></tr></thead><tbody>';
            for (var n = 0; n < data.medication.length; n++) {
                medicationStr += '<tr class="medication' + (n + 1) + '">' +
                    '<td>' + checkUndefined(data.medication[n].start_time) + '<input type="hidden" value="' + checkUndefined(data.medication[n].start_time) + '" class="drugsdate" name="drugsdate[]"></td>' +
                    '<td>' + checkUndefined(data.medication[n].end_time) + '<input type="hidden" value="' + checkUndefined(data.medication[n].end_time) + '" class="drugsenddate" name="drugsenddate[]"></td>' +
                    '<td>' + checkUndefined(data.medication[n].name) + '<input type="hidden" value="' + checkUndefined(data.medication[n].name) + '" class="drugsid" name="drugsid[]"></td>';
                if (data.medication[n].dosage.type == '每次剂量') {
                    medicationStr += '<td>' + checkUndefined(data.medication[n].dosage.value) + '<input type="hidden" class="dose" value="' + checkUndefined(data.medication[n].dosage.value) + '" name="dose[]"></td>';
                } else if (data.medication[n].dosage.type == '分次剂量') {
                    medicationStr += '<td><span>早上' + checkUndefined(data.medication[n].dosage.values.morning) + '</span><input type="hidden" class="morning" value="' + checkUndefined(data.medication[n].dosage.values.morning) + '" name="morning[]"> ' +
                        '<span> 中午' + checkUndefined(data.medication[n].dosage.values.atnoon) + '</span><input type="hidden" class="atnoon" value="' + checkUndefined(data.medication[n].dosage.values.atnoon) + '" name="atnoon[]"> ' +
                        '<span> 晚上' + checkUndefined(data.medication[n].dosage.values.evening) + '</span><input type="hidden" class="evening" value="' + checkUndefined(data.medication[n].dosage.values.evening) + '" name="evening[]"> ' +
                        '<span> 睡前' + checkUndefined(data.medication[n].dosage.values.before_sleep) + '</span><input type="hidden" class="sleep" value="' + checkUndefined(data.medication[n].dosage.values.before_sleep) + '" name="sleep[]"></td>';
                }
                medicationStr += '<td>' + checkUndefined(data.medication[n].dosage.unit) + ' <input type="hidden" class="unit" value="' + checkUndefined(data.medication[n].dosage.unit) + '" name="unit[]"></td>' +
                    '<td>' + checkUndefined(data.medication[n].usage) + '<input type="hidden" class="usage" value="' + checkUndefined(data.medication[n].usage) + '" name="usage[]"></td>' +
                    '<td>' + checkUndefined(data.medication[n].frequency) + '<input type="hidden" class="frequency" value="' + checkUndefined(data.medication[n].frequency) + '" name="frequency[]"></td>' +
                    '<td>' + checkUndefined(data.medication[n].remark) + '<input type="hidden" class="remark" value="' + checkUndefined(data.medication[n].remark) + '" name="remark[]"></td>' +
                    '<td><button type="button" class="btn btn-outline btn-primary margin-right-5 editMedicationBtn" data-toggle="modal" data-target="#addMedication" data-id="zsAddMedication1" data-edit="medication' + (n + 1) + '">编辑</button>' +
                    '<button type="button" class="btn btn-outline btn-danger addMedicationDelete">删除</button></td></tr>';
            }
            medicationStr += '</tbody></table>';
            // $('#zhusu #jwsAddMedication1').html(medicationStr);
            $('#zhusu #zsAddMedication1').html(medicationStr);
        }
        // $('#zhusu textarea').val(data.remark);
        // 川↑

        $('#zhusu input.zsId').val(data.id);
        if (data.symptoms) {
            $.each(data.symptoms, function (i, v) {
                i = parseInt(i);
                $('#zs_symptom #zsGrop_' + (i + 1)).find('input.started_at').val(v.started_at);
                $('#zs_symptom #zsGrop_' + (i + 1)).find('input.exacerbated_at').val(v.exacerbated_at);
                if (v.name) {
                    for (var q = 0, str = ''; q < v.name.length; q++) {
                        str += '<li class="tag-selected with-x" data-id="symptomName" data-name="' + v.name[q] + '"><input type="hidden" value="' + v.name[q] + '" name="symptom[]">' + v.name[q] + '<i>×</i></li>'
                    }
                }
                $('#zs_symptom #zsGrop_' + (i + 1)).find('ul.sui-tag').html(str);
                if ($('#zs_symptom #zsGrop_' + (i + 1)).css('display') != 'block') {
                    $('#zs_symptom #zsGrop_' + (i + 1)).css('display', 'block');
                }
            });
            if (data.symptoms.length >= 5) {
                $('#addZsSymptom').addClass('disabled');
                $('#addZsSymptom').attr('disabled', 'disabled');
            }
        }
        if (data.weightchange) {
            $('#zhusu .weight-change').find('select[name="weightchange"]').val(data.weightchange.key);
            if (data.weightchange.key != 0) {
                $('#zhusu .weight-change .zsWeightChangeSize').css('display', 'block');
            }
        }
        if (data.weightchangestatus) {
            $('#zhusu .weight-change select[name="weightchangestatus"]').val(data.weightchangestatus.key);
            if (data.weightchangestatus.key == 2) {
                $('#zhusu .weight-change .zsWeightChangeSize input').css('display', 'none');
                $('#zhusu .weight-change .zsWeightChangeSize span').css('display', 'none');
            } else {
                $('#zhusu .weight-change .zsWeightChangeSize input').val(data.weightchangekg);
            }
        }
        if (data.blood_glucose) {
            $('#zhusu .bloodSugar .limosis_low').val(data.blood_glucose.limosis.low);
            $('#zhusu .bloodSugar .limosis_high').val(data.blood_glucose.limosis.high);
            $('#zhusu .bloodSugar .postprandial_low').val(data.blood_glucose.postprandial.low);
            $('#zhusu .bloodSugar .postprandial_high').val(data.blood_glucose.postprandial.high);
        }
        $('#zhusu textarea').val(data.remark);
    }//主诉  处理数据方法  end
    //现病史  处理数据方法  start
    function hpi(data) {
        $('#xianbingshi input.xbsId').val(data.id);
        //放置  一般情况数据
        if (data.diet) {
            $('#xianbingshi .xbs-table div[data-name="staple"]').find('input').val(data.diet.staple);
            var tdFirst = $('#xianbingshi .xbs-table td[data-name="diet"] div.xgb-foods-type');
            for (var i = 0; i < tdFirst.length; i++) {
                var tdKey = $(tdFirst[i]).attr('data-name');
                if (data.diet[tdKey] != 2) {
                    $(tdFirst[i]).find('input[value="' + data.diet[tdKey] + '"]').attr('checked', 'checked');
                    $(tdFirst[i]).find('input[value="2"]').removeAttr('checked');
                }
            }
        }
        if (data.normal) {
            var tdNormal = $('#xianbingshi .xbs-table td[data-name="normal"] div.xgb-foods-type');
            for (var j = 0; j < tdNormal.length; j++) {
                var tdNormalKey = $(tdNormal[j]).attr('data-name');
                var type = $(tdNormal[j]).attr('data-type');
                if (type == 'obj') {
                    $(tdNormal[j]).find('.form-control').val(data.normal[tdNormalKey][$(tdNormal[j]).find('.form-control').attr('data-name')]);
                } else {
                    if (data.normal[tdNormalKey] != 1) {
                        $(tdNormal[j]).find('input[value="' + data.normal[tdNormalKey] + '"]').attr('checked', 'checked');
                        $(tdNormal[j]).find('input[value="1"]').removeAttr('checked');
                    }
                }
            }
        }
        $('#xianbingshi .xbs-table td[data-name="sport"] .form-control').val(data.sport);
        //放置现病史组  数据  S
        var xbsGroupData = data.sub.data;
        for (var q = 0; q < xbsGroupData.length; q++) {
            var xbsGroupDiv = $('#xianbingshi #xbsGroupList>div#xbsAddGroup' + q);
            xbsGroupDiv.find('input.xbsGroupId').val(xbsGroupData[q].id);
            xbsGroupDiv.find('div.xbsGroupSaveBox').removeClass('display-none');
            if (xbsGroupDiv.css('display') != 'block') {
                xbsGroupDiv.css('display', 'block');
            }
            //起病日期到症状
            xbsGroupDiv.find('div[data-name="started_at"] .form-control').val(xbsGroupData[q].started_at);
            xbsGroupDiv.find('div[data-name="inducement"] .form-control').val(xbsGroupData[q].inducement.key);
            xbsGroupDiv.find('div[data-name="clinic_site"] .form-control').val(xbsGroupData[q].clinic_site);
            var sympotmStr = '';
            for (var m = 0; m < xbsGroupData[q].symptoms.length; m++) {
                sympotmStr += '<li class="tag-selected with-x" data-id="symptomName" data-name="' + xbsGroupData[q].symptoms[m] + '"><input type="hidden" value="' + xbsGroupData[q].symptoms[m] + '" name="symptom[]">' + xbsGroupData[q].symptoms[m] + '<i>×</i></li>';
            }
            xbsGroupDiv.find('ul.sui-tag').html(sympotmStr);
            //放置  血糖数据
            var bloodInput = xbsGroupDiv.find('div.bloodInput');
            for (var s = 0; s < bloodInput.length; s++) {
                var bloodKey = $(bloodInput[s]).attr('data-name');
                var bloodInputBox = $(bloodInput[s]).find('div[data-name]');
                for (var p = 0; p < bloodInputBox.length; p++) {
                    var bloodInputBoxKey = $(bloodInputBox[p]).attr('data-name');
                    if (bloodInputBoxKey == 'hba1c') {
                        $(bloodInputBox[p]).find('input').val(xbsGroupData[q][bloodKey].hba1c)
                    } else {
                        $(bloodInputBox[p]).find('input[data-name="low"]').val(xbsGroupData[q][bloodKey][bloodInputBoxKey].low);
                        $(bloodInputBox[p]).find('input[data-name="high"]').val(xbsGroupData[q][bloodKey][bloodInputBoxKey].high);
                    }
                }
            }
            //放置添加诊断表格数据  S
            if (xbsGroupData[q].diagnose.length) {
                var zdStr = '<table class="table-bordered table-striped table-hover text-center diagnosis-table"><thead><tr><th>病名</th><th>ICD编码</th><th>操作</th></tr></thead><tbody>';
                $.each(xbsGroupData[q].diagnose, function (I, V) {
                    zdStr += '<tr><td>' + V.name + ' <input type="hidden" name="diagnose[]" value="' + V.id + '"></td>' +
                        '<td>' + V.icd + '</td><td>' +
                        '<button type="button" class="btn btn-outline btn-danger deleteDiagnosisBtn">删除</button></td></tr>';
                });
                zdStr += '</tbody></table>';
                xbsGroupDiv.find('div.xbsAddDiagnosis').html(zdStr);
            }
            //放置添加诊断表格数据  E
            //放置添加用药数据  S
            if (xbsGroupData[q].medication) {
                var medicationStr = '<table class="table-bordered table-striped table-hover text-center medicationList-table"><thead><tr><th>开始时间</th><th>结束时间</th><th>名称</th><th>剂量</th><th>单位</th><th>用法</th><th>频次</th><th>其他备注</th><th>操作</th></tr></thead><tbody>';
                for (var n = 0; n < xbsGroupData[q].medication.length; n++) {
                    medicationStr += '<tr class="medication' + (n + 1) + '">' +
                        '<td>' + checkUndefined(xbsGroupData[q].medication[n].start_time) + '<input type="hidden" value="' + xbsGroupData[q].medication[n].start_time + '" class="drugsdate" name="drugsdate[]"></td>' +
                        '<td>' + checkUndefined(xbsGroupData[q].medication[n].end_time) + '<input type="hidden" value="' + xbsGroupData[q].medication[n].end_time + '" class="drugsenddate" name="drugsenddate[]"></td>' +
                        '<td>' + checkUndefined(xbsGroupData[q].medication[n].name) + '<input type="hidden" value="' + xbsGroupData[q].medication[n].name + '" class="drugsid" name="drugsid[]"></td>';
                    if (xbsGroupData[q].medication[n].dosage.type == '每次剂量') {
                        medicationStr += '<td>' + checkUndefined(xbsGroupData[q].medication[n].dosage.value) + '<input type="hidden" class="dose" value="' + xbsGroupData[q].medication[n].dosage.value + '" name="dose[]"></td>';
                    } else if (xbsGroupData[q].medication[n].dosage.type == '分次剂量') {
                        medicationStr += '<td><span>早上' + checkUndefined(xbsGroupData[q].medication[n].dosage.values.morning) + '</span><input type="hidden" class="morning" value="' + xbsGroupData[q].medication[n].dosage.values.morning + '" name="morning[]"> ' +
                            '<span> 中午' + checkUndefined(xbsGroupData[q].medication[n].dosage.values.atnoon) + '</span><input type="hidden" class="atnoon" value="' + xbsGroupData[q].medication[n].dosage.values.atnoon + '" name="atnoon[]"> ' +
                            '<span> 晚上' + checkUndefined(xbsGroupData[q].medication[n].dosage.values.evening) + '</span><input type="hidden" class="evening" value="' + xbsGroupData[q].medication[n].dosage.values.evening + '" name="evening[]"> ' +
                            '<span> 睡前' + checkUndefined(xbsGroupData[q].medication[n].dosage.values.before_sleep) + '</span><input type="hidden" class="sleep" value="' + xbsGroupData[q].medication[n].dosage.values.before_sleep + '" name="sleep[]"></td>';
                    }
                    medicationStr += '<td>' + checkUndefined(xbsGroupData[q].medication[n].dosage.unit) + ' <input type="hidden" class="unit" value="' + xbsGroupData[q].medication[n].dosage.unit + '" name="unit[]"></td>' +
                        '<td>' + checkUndefined(xbsGroupData[q].medication[n].usage) + '<input type="hidden" class="usage" value="' + xbsGroupData[q].medication[n].usage + '" name="usage[]"></td>' +
                        '<td>' + checkUndefined(xbsGroupData[q].medication[n].frequency) + '<input type="hidden" class="frequency" value="' + xbsGroupData[q].medication[n].frequency + '" name="frequency[]"></td>' +
                        '<td>' + checkUndefined(xbsGroupData[q].medication[n].remark) + '<input type="hidden" class="remark" value="' + xbsGroupData[q].medication[n].remark + '" name="remark[]"></td>' +
                        '<td><button type="button" class="btn btn-outline btn-primary margin-right-5 editMedicationBtn" data-toggle="modal" data-target="#addMedication" data-id="xbsAddMedication' + q + '" data-edit="medication' + (n + 1) + '">编辑</button>' +
                        '<button type="button" class="btn btn-outline btn-danger addMedicationDelete">删除</button></td></tr>';
                }
                medicationStr += '</tbody></table>';
                xbsGroupDiv.find('div.xbsAddMedication').html(medicationStr);
            }
            //放置添加用药数据  E
            //放置汤药详情数据  S
            if (xbsGroupData[q].cn_medication && xbsGroupData[q].cn_medication.length) {
                var tcmStr = '<table class="table-bordered table-striped table-hover text-center tcm-table"><thead><tr><th>名称剂量</th><th>煎服方法</th><th>操作</th></tr></thead><tbody>';
                $.each(xbsGroupData[q].cn_medication, function (I, V) {
                    if (V.type != 3) {
                        tcmStr += '<tr class="tcm' + (I + 1) + '"><td>';
                        for (var s = 0; s < V.drugs.length; s++) {
                            tcmStr += '<span>' + checkUndefined(V.drugs[s].name) + checkUndefined(V.drugs[s].weight) + 'g <input type="hidden" value="' + checkUndefined(V.drugs[s].name) + '" class="tableSelectTcm" data-num="' + checkUndefined(V.drugs[s].weight) + '"></span>'
                        }
                        tcmStr += '</td><td>煎法：' + checkUndefined(V.usage) + ' 频次：' + checkUndefined(V.dosage) + '，' + checkUndefined(V.frequency) + ' 总数：' + checkUndefined(V.dose) + '付' +
                            '<input type="hidden" class="takMethod" value="' + checkUndefined(V.usage) + '">' +
                            '<input type="hidden" class="frequency1" value="' + checkUndefined(V.dosage) + '">' +
                            '<input type="hidden" class="frequency2" value="' + checkUndefined(V.frequency) + '">' +
                            '<input type="hidden" class="total" value="' + checkUndefined(V.dose) + '"></td><td>' +
                            '<button type="button" class="btn btn-outline btn-primary margin-right-5 addTcmEdit" data-toggle="modal" data-target="#addTcm" data-id="xbsAddTcm' + q + '" data-edit="tcm' + (I + 1) + '">编辑</button>' +
                            '<button type="button" class="btn btn-outline btn-danger addTcmDelete">删除</button></td></tr>';
                    } else {
                        var title = V.name;
                        var times = V.times_per_day;
                        var numMe = V.quantity_per_times;
                        var boxNum = V.total;
                        var stime = V.start_time;
                        var etime = V.end_time;
                        var unit = V.quantity_unit;
                        tcmStr += '<tr class="tcm' + (I + 1) + '" data-type="3" ><td><span>' + title +
                            '<input type="hidden" value="' + title + '" class="tableSelectTcm"></span>';

                        var sDataText, eDataText;
                        sDataText = (stime !== "") ? ( "， 开始时间：") : "";
                        eDataText = (etime !== "") ? (" 结束时间：") : "";
                        tcmStr += '</td><td>每日：' + times + ' 次， 每次：' + numMe + unit + '，总数：' + boxNum + '盒' + sDataText + stime + eDataText + etime +
                            '<input type="hidden" class="stime" value="' + stime + '">' +
                            '<input type="hidden" class="etime" value="' + etime + '">' +
                            '<input type="hidden" class="times" value="' + times + '">' +
                            '<input type="hidden" class="numMe" value="' + numMe + '"><' +
                            'input type="hidden" class="unit" value="' + unit + '"><' +
                            'input type="hidden" class="boxNum" value="' + boxNum + '"></td>';
                        tcmStr += '<td class="">' +
                            '<button type="button" class="btn btn-outline btn-primary margin-right-5 addTcmEdit"  data-toggle="modal" data-target="#addTcm" data-id="xbsAddTcm' + q + '" data-edit="tcm' + (I + 1) + '">编辑</button>' +
                            '<button type="button" class="btn btn-outline btn-danger addTcmDelete">删除</button></td>';
                    }


                });
                tcmStr += '</tbody></table>';
                xbsGroupDiv.find('div.xbsAddTcm').html(tcmStr);
            }
            //放置汤药详情数据  E
        }


        if (xbsGroupData.length == '5') {
            $('#addHpiGroup').addClass('disabled');
            $('#addHpiGroup').attr('disabled', 'disabled');
        }
        //放置现病史组  数据  E
        $('#xianbingshi textarea').val(data.remark);
        //甲状腺放置数据⬇️
        if (data.thyroid) {
            if (data.thyroid.started_at) {
                $(".thyroidStarted_at").val(data.thyroid.started_at)
            }
            if (data.thyroid.symptoms_remark) {
                $(".thyroid_symptoms_remark").val(data.thyroid.symptoms_remark)
            }
            if (data.thyroid.examination_remark) {
                $(".examination_remark").val(data.thyroid.examination_remark)
            }
            if (data.thyroid.hyperthyroidism_remark) {
                $(".hyperthyroidism_remark").val(data.thyroid.hyperthyroidism_remark)
            }
            if (data.thyroid.inducement) {
                $(".thyroidInducement option[value=" + data.thyroid.inducement + "]").attr("selected", "selected")
            }
            if (data.thyroid.symptoms) {
                $("ul.thyroid").html(appendLi(data.thyroid.symptoms))
            }
            ;
            if (data.thyroid.examination) {
                $("ul.thyroid1").html(appendLi(data.thyroid.examination))
            }
            ;
            if (data.thyroid.hyperthyroidism) {
                $("ul.thyroid2").html(appendLi(data.thyroid.hyperthyroidism))
            }
            ;
        }

        //高血压数据放置⬇️
        if (data.adrenal_gland) {
            if (data.adrenal_gland.started_at) {
                $("#highBlood").find(".started_at").val(data.adrenal_gland.started_at)
            }
            if (data.adrenal_gland.symptoms_remark) {
                $(".symptoms_remark").val(data.adrenal_gland.symptoms_remark)
            }
            if (data.adrenal_gland.accompanied_symptom_remark) {
                $(".accompanied_symptom_remark").val(data.adrenal_gland.accompanied_symptom_remark)
            }
            if (data.adrenal_gland.hyperthyroidism) {
                $("ul.highBlood").html(appendLi(data.adrenal_gland.symptoms))
            }
            ;
            if (data.adrenal_gland.accompanied_symptom) {
                $("ul.highBlood1").html(appendLi(data.adrenal_gland.accompanied_symptom))
            }
            if (data.adrenal_gland.symptoms) {
                $("ul.highBlood").html(appendLi(data.adrenal_gland.symptoms))
            }
            ;

        }


    }

    function appendLi(data) {
        var html = "";
        $.each(data, function (k, v) {
            html += '<li class="tag-selected with-x" data-id="symptomName" data-name="' + v + '"><input type="hidden" value="' + v + '" name="symptom[]">' + v + '<i>×</i></li>';
        });
        return html;
    }

    //现病史  处理数据方法  end
    //既往史  处理数据方法  start
    function past(data) {
        $('#jiwangshi input.jwsId').val(data.id);
        //放置药物数据
        var drugsList = $('#jiwangshi .medicalHistory-table td.drugList');
        for (var i = 0; i < drugsList.length; i++) {
            var key = $(drugsList[i]).attr('data-name');
            if (data[key] && data[key].drugs) {
                var drugs = data[key]['drugs'];
                var str = '';
                for (var q = 0; q < drugs.length; q++) {
                    str += '<li class="tag-selected with-x"><input type="hidden" value="' + drugs[q] + '" name="symptom[]">' + drugs[q] + '<i>×</i></li>'
                }
                $(drugsList[i]).find('ul.sui-tag').html(str);
            }
        }
        //放置输入框数据
        var inputList = $('#jiwangshi .medicalHistory-table td.inputList');
        for (var s = 0; s < inputList.length; s++) {
            var inputKey = $(inputList[s]).attr('data-name');
            if (data[inputKey]) {
                var inputVal = $(inputList[s]).find('.form-control');
                for (var z = 0; z < inputVal.length; z++) {
                    var inputName = $(inputVal[z]).attr('data-name');
                    $(inputVal[z]).val(data[inputKey][inputName]);
                }
            }
        }
        //放置冠心病史数据
        $('div.medicalHistory-box.coronary_disease input[name="jws_coronaryheartyear"]').val(data.coronary_disease.time);
        $('div.medicalHistory-box.coronary_disease input[name="jws_bypasstime"]').val(data.coronary_disease.cabg);
        if (data.coronary_disease.stenting) {
            var tableTtr = '<table class="table-bordered table-striped table-hover text-center stentsTime-table"><thead><tr><th>置入时间</th><th>操作</th></tr></thead><tbody>';
            for (var t = 0; t < data.coronary_disease.stenting.length; t++) {
                tableTtr += '<tr><td>' + data.coronary_disease.stenting[t] + '<input type="hidden" name="stentsDate[]" value="' + data.coronary_disease.stenting[t] + '"></td><td><button type="button" class="btn btn-outline btn-danger stentsTimeDelete">删除</button></td></tr>';
            }
            tableTtr += '</tbody></table>';
            $('#jwsStentsPlacementTime').html(tableTtr);
        }
        //放置手术史数据
        if (data.operation) {
            var operationStr = '<table class="table-bordered table-striped table-hover text-center medicationList-table"><thead><tr><th>手术日期</th><th>手术名称</th><th>操作</th></tr></thead><tbody>';
            for (var m = 0; m < data.operation.length; m++) {
                operationStr += '<tr class="surgery' + (m + 1) + '"><td>' + data.operation[m].time + '<input type="hidden" class="surgery-date" value="' + data.operation[m].time + '" name="surgeryDate[]"></td>' +
                    '<td>' + data.operation[m].name + '<input type="hidden" class="surgery-name" value="' + data.operation[m].name + '" name="surgeryDate[]"></td>' +
                    '<td><button type="button" class="btn btn-outline btn-primary margin-right-5 jwsEditSurgeryBtn" data-toggle="modal" data-target="#addSurgery" data-edit="surgery' + (m + 1) + '" data-id="jwsAddSurgery">编辑</button>' +
                    '<button type="button" class="btn btn-outline btn-danger surgeryDelete">删除</button></td></tr>';
            }
            operationStr += '</tbody></table>';
            $('#jiwangshi #jwsAddSurgery').html(operationStr);
        }
        //放置用药史数据
        if (data.medication) {
            var medicationStr = '<table class="table-bordered table-striped table-hover text-center medicationList-table"><thead><tr><th>开始时间</th><th>结束时间</th><th>名称</th><th>剂量</th><th>单位</th><th>用法</th><th>频次</th><th>其他备注</th><th>操作</th></tr></thead><tbody>';
            for (var n = 0; n < data.medication.length; n++) {
                medicationStr += '<tr class="medication' + (n + 1) + '">' +
                    '<td>' + checkUndefined(data.medication[n].start_time) + '<input type="hidden" value="' + data.medication[n].start_time + '" class="drugsdate" name="drugsdate[]"></td>' +
                    '<td>' + checkUndefined(data.medication[n].end_time) + '<input type="hidden" value="' + data.medication[n].end_time + '" class="drugsenddate" name="drugsenddate[]"></td>' +
                    '<td>' + checkUndefined(data.medication[n].name) + '<input type="hidden" value="' + data.medication[n].name + '" class="drugsid" name="drugsid[]"></td>';
                if (data.medication[n].dosage.type == '每次剂量') {
                    medicationStr += '<td>' + checkUndefined(data.medication[n].dosage.value) + '<input type="hidden" class="dose" value="' + data.medication[n].dosage.value + '" name="dose[]"></td>';
                } else if (data.medication[n].dosage.type == '分次剂量') {
                    medicationStr += '<td><span>早上' + checkUndefined(data.medication[n].dosage.values.morning) + '</span><input type="hidden" class="morning" value="' + data.medication[n].dosage.values.morning + '" name="morning[]"> ' +
                        '<span> 中午' + checkUndefined(data.medication[n].dosage.values.atnoon) + '</span><input type="hidden" class="atnoon" value="' + data.medication[n].dosage.values.atnoon + '" name="atnoon[]"> ' +
                        '<span> 晚上' + checkUndefined(data.medication[n].dosage.values.evening) + '</span><input type="hidden" class="evening" value="' + data.medication[n].dosage.values.evening + '" name="evening[]"> ' +
                        '<span> 睡前' + checkUndefined(data.medication[n].dosage.values.before_sleep) + '</span><input type="hidden" class="sleep" value="' + data.medication[n].dosage.values.before_sleep + '" name="sleep[]"></td>';
                }
                medicationStr += '<td>' + checkUndefined(data.medication[n].dosage.unit) + ' <input type="hidden" class="unit" value="' + data.medication[n].dosage.unit + '" name="unit[]"></td>' +
                    '<td>' + checkUndefined(data.medication[n].usage) + '<input type="hidden" class="usage" value="' + data.medication[n].usage + '" name="usage[]"></td>' +
                    '<td>' + checkUndefined(data.medication[n].frequency) + '<input type="hidden" class="frequency" value="' + data.medication[n].frequency + '" name="frequency[]"></td>' +
                    '<td>' + checkUndefined(data.medication[n].remark) + '<input type="hidden" class="remark" value="' + data.medication[n].remark + '" name="remark[]"></td>' +
                    '<td><button type="button" class="btn btn-outline btn-primary margin-right-5 editMedicationBtn" data-toggle="modal" data-target="#addMedication" data-id="jwsAddMedication" data-edit="medication' + (n + 1) + '">编辑</button>' +
                    '<button type="button" class="btn btn-outline btn-danger addMedicationDelete">删除</button></td></tr>';
            }
            medicationStr += '</tbody></table>';
            $('#jiwangshi #jwsAddMedication').html(medicationStr);
        }
        $('#jiwangshi textarea').val(data.remark);

        //既往史病史的数据注入⬇️
        var htmlStr = '';
        if (data.extra) {
            $.each(data.extra, function (k, v) {
                var drugsHtml = '';
                if (v.drugs) {
                    $.each(v.drugs, function (m, n) {
                        drugsHtml += '<li class="tag-selected with-x"><input type="hidden" value="' + n + '" name="symptom[]">' + n + '<i>×</i></li>'
                    });
                }
                htmlStr += '<tr><td data-id="' + k + '" data-name="extra[' + k + ']" class="inputList bg-default removeTd">' + v.name + '<input  class="form-control input-text" type="hidden" value="' + v.name + '" name="name" data-name="name"><br></td>' +
                    '<td data-id="' + k + '" class="inputList removeTd" data-name="extra[' + k + ']">' +
                    '<div class="medicalHistory-box">' +
                    '<span class="input-title">时间</span>' +
                    '<input type="text" data-name="time" name="jws_newDate" value="' + v.time + '" class="form-control input-text maxMonth" placeholder="请选择时间" data-toggle="datepicker">' +
                    '</div>' +
                    '<div class="medicalHistory-box  margin-top-10">' +
                    '<span class="input-title">备注</span>' +
                    '<input type="text" data-name="remark" value="' + v.remark + '" name="remark" class="form-control input-text" maxlength="50" placeholder="请添加备注">' +
                    '</div>' +
                    '</td>' +
                    '<td data-id="' + k + '" class="drugList removeTd" data-name="extra[' + k + ']">' +
                    '<div id="newAddDrug' + k + '">' +
                    '<ul class="sui-tag">' + drugsHtml +
                    '</ul>' +
                    '</div>' +
                    '<button type="button" class="btn btn-outline btn-primary selectDrugBtn" data-toggle="modal" data-target="#selectDrugs" data-id="newAddDrug' + k + '">选择药物' +
                    '</button>' +
                    '</td><td><button style="margin-top: 10px;" data-id="' + k + '" class="btn btn-outline btn-danger addDelete">删除</button>' +
                    '</td>' +
                    '</tr>';
            });

        }
        $("#jiwangshi").find("table.medicalHistory-table>tbody").append(htmlStr);


    }//既往史  处理数据方法  end
    //个人史  处理数据方法  start
    function person(data) {
        $('#gerenshi input.gerId').val(data.id);
        if (data.smoke) {
            $('#gerenshi input[name="smoke[time]"]').val(data.smoke.time);
            if (data.smoke.time) {
                $('#gerenshi #smokeTime input').val(data.smoke.many);
                $('#gerenshi #smokeTime').removeClass('display-none');
            }

        }
        $('#gerenshi input[name="stop_smoke"]').val(data.stop_smoke);
        if (data.drink) {
            $('#gerenshi input[name="drink[time]"]').val(data.drink.time);
            if (data.drink.time) {
                $('#gerenshi #drinkTime input.whiteSpirit').val(data.drink.whiteSpirit);
                $('#gerenshi #drinkTime input.redSpirit').val(data.drink.redSpirit);
                $('#gerenshi #drinkTime input.beer').val(data.drink.beer);
                if (data.drink.frequency == 2) {
                    $('#gerenshi #drinkTime input[value="2"]').attr('checked', 'checked');
                    $('#gerenshi #drinkTime input[value="1"]').removeAttr('checked');
                }
                if (data.drink.time) {
                    $('#gerenshi #drinkTime').removeClass('display-none');
                }
            }
        }
        $('#gerenshi input[name="stop_drink"]').val(data.stop_drink);

        $('#gerenshi textarea').val(data.remark);
    }//个人史  处理数据方法  end
    //月经婚育史  处理数据方法  start
    function marriage(data) {
        $('#hunyushi input.hysId').val(data.id);
        if (data.marriage) {
            $('#hunyushi input[name="marriage[time]"]').val(data.marriage.time);
            $('#hunyushi input[name="marriage[son]"]').val(data.marriage.son);
            $('#hunyushi input[name="marriage[daughter]"]').val(data.marriage.daughter);
        }
        if (data.macrosomia) {
            $('#hunyushi td.macrosomia').find('input[value="' + data.macrosomia.key + '"]').attr('checked', true).siblings().removeAttr('checked');
        }
        if (data.menstruation) {
            $('#hunyushi input[name="menstruation[menarche]"]').val(data.menstruation.menarche);
            $('#hunyushi input[name="menstruation[period][days]"]').val(data.menstruation.period.days);
            $('#hunyushi select[name="menstruation[period][law]"]').val(data.menstruation.period.law.key);
            $('#hunyushi input[name="menstruation[cycle][days]"]').val(data.menstruation.cycle.days);
            $('#hunyushi select[name="menstruation[cycle][law]"]').val(data.menstruation.cycle.law.key);
            $('#hunyushi select[name="menstruation[menstrual_volume]"]').val(data.menstruation.menstrual_volume);
            $('#hunyushi input[name="menstruation[last_time][date]"]').val(data.menstruation.last_time.date);
            $('#hunyushi input[name="menstruation[last_time][continue]"]').val(data.menstruation.last_time.continue);
        }
        if (data.menopause) {
            $('#hunyushi input[name="menopause[age]"]').val(data.menopause.age);
        }
        $('#hunyushi textarea').val(data.remark);
    }//月经婚育史  处理数据方法  end
    //家族史  处理数据方法  start
    function family(data) {
        $('#jiazushi input.jzsId').val(data.id);

        function cycleAdd(obj, parent) {
            $.each(obj, function (i, v) {
                if (v == 1) {
                    $('input[data-parent="' + parent + '"][name="' + i + '"]').attr('checked', 'checked');
                }
            });
        }

        function parentAdd(parent, obj1, obj2) {
            $('#jzs_list input[data-id="' + parent + '"]').attr('checked', 'checked');
            $('#jzs_list #' + parent + '').removeClass('display-none');
            cycleAdd(obj1, parent);
            cycleAdd(obj2, parent);
        }

        if (data.diabetes.select == 1) {
            parentAdd('diabetes', data.diabetes.lineal, data.diabetes.notLineal);
        }
        if (data.chd.select == 1) {
            parentAdd('chd', data.chd.lineal, data.chd.notLineal);
        }
        if (data.embolism.select == 1) {
            parentAdd('embolism', data.embolism.lineal, data.embolism.notLineal);
        }
        if (data.hyperlipidemia.select == 1) {
            parentAdd('hyperlipidemia', data.hyperlipidemia.lineal, data.hyperlipidemia.notLineal);
        }
        if (data.hypertension.select == 1) {
            parentAdd('hypertension', data.hypertension.lineal, data.hypertension.notLineal);
        }
        if (data.tumor.select == 1) {
            parentAdd('tumor', data.tumor.lineal, data.tumor.notLineal);
        }
        var relativesNmae = {
            father: '父',
            mother: '母',
            brother: '兄弟',
            sister: '姐妹',
            children: '子女',
            grandfather: '爷爷',
            grandma: '奶奶',
            grandmother: '姥姥',
            grandpa: '姥爷',
            other: '其他亲属',
            uncle: '叔叔',
            wifeSister: '姨',
            aunt: '姑姑',
            motherBrother: '舅舅'
        };
        if (data.extend) {
            for (var num = 0; num < data.extend.length; num++) {
                var str = '<tr class="familyHistory jzs-' + num + '" data-type="extend"><td class="jzsTabel-title">家族史名称</td><td colspan="3" class="jzsCase-name"><label>' +
                    '<input type="checkbox" name="jzs-' + num + '" checked disabled data-name="' + data.extend[num].name + '">(亲属)患' + data.extend[num].name + '</label>' +
                    '<button type="button" class="btn btn-outline btn-danger jzs-delete" data-tr="jzs-' + num + '">删除</button></td></tr>' +
                    '<tr class="jzs-' + num + '"><td class="jzsTabel-title">直系亲属</td><td>';
                $.each(data.extend[num].lineal, function (i, v) {
                    if (v == 1) {
                        str += '<label><input type="checkbox" data-type="lineal" data-num="' + num + '" name="' + i + '" checked/> ' + relativesNmae[i] + '</label>';
                    } else {
                        str += '<label><input type="checkbox" data-type="lineal" data-num="' + num + '" name="' + i + '"/> ' + relativesNmae[i] + '</label>';
                    }
                });
                str += '<td class="jzsTabel-title">非直系亲属</td><td>';
                $.each(data.extend[num].notLineal, function (i, v) {
                    if (v == 1) {
                        str += '<label><input type="checkbox" data-type="notLineal" data-num="' + num + '" name="' + i + '" checked/> ' + relativesNmae[i] + '</label>';
                    } else {
                        str += '<label><input type="checkbox" data-type="notLineal" data-num="' + num + '" name="' + i + '"/> ' + relativesNmae[i] + '</label>';
                    }
                });
                str += '</td></tr>';
                $('#jzs_list').append(str);
            }
            if (data.extend.length == 6) {
                var addJzsCaseBtn = $('#jiazushi button[data-target="#addJzsCase"]');
                addJzsCaseBtn.addClass('disabled');
                addJzsCaseBtn.attr('disabled', 'disabled');
            }
        }
        $('#jiazushi textarea').val(data.remark);
    }//家族史  处理数据方法  end
    //标签点击 请求数据  start
    $('#addCaseNavTabs li[data-js="caseFirst"]').click(function () {
        var isSave = $(this).attr('data-save');
        var isLoad = $(this).attr('data-load');
        var tabPage = $(this).attr('data-href');
        if ((isLoad == 'no') && (isSave == 'yes')) {
            beforeGetData(tabPage);
        }
    });//标签点击 请求数据  end

    //患者性别为男  禁用月经婚育史 否则 取消禁用  start
    $('#sexSelect').change(function () {
        var yjhysTab = $('#yjhysTab');
        if ($(this).val() == 1) {
            yjhysTab.removeClass('disabled').attr('data-toggle', 'tab');
            $('#is_gestation').removeAttr('disabled');
            $('#is_gestation').find('option[value="0"]').attr('disabled', 'disabled');
            $('#is_gestation').val(1);
            $("#hunyushi").find("tr.manHide,td.manHide").show();

        } else {
            // 男性也可以点击月经婚育史⬇️
            $("#hunyushi").find("tr.manHide,td.manHide").hide();
            // yjhysTab.addClass('disabled').attr('data-toggle', '');
            $('#is_gestation').attr('disabled', 'disabled');
            $('#baseMessageForm').find('select[name="is_gestation"]').val(0);

            // 如果当前为在月经婚育史上，此时切换性别为男，不需要进行tab切换操作了⬇️
            // if (yjhysTab.parent().hasClass('active')) {
            //     yjhysTab.parent().removeClass('active');
            //     yjhysTab.parent().next().addClass('active');
            //     var id = yjhysTab.parent().next().find('a').attr('href');
            //     $(id).addClass('active').prev().removeClass('active');
            // }
        }
    });//患者性别为男  禁用月经婚育史 否则 取消禁用  end


    //家族史 家族病点击 start
    $('.jzsCase-table').delegate('.jzsCase-btn', 'click', function () {
        var id = $(this).attr('data-id');
        if ($(this).is(':checked')) {
            $('#' + id).show(300);
        } else {
            $('#' + id).hide(300);
        }
    });//家族史 家族病点击 end
    //家族史 追加的家族史删除按钮 start
    $('.jzsCase-table').delegate('.jzs-delete', 'click', function () {
        var delTr = $(this).attr('data-tr');
        $.confirm({
            title: '温馨提示',
            body: '确认要删除吗？',
            okBtn: '确定',
            cancelBtn: '取消',
            transition: true,
            okHidden: function () {
                $('#jzs_list').find('tr.' + delTr).remove();
                if ($('#jiazushi button[data-target="#addJzsCase"]').hasClass('disabled')) {
                    $('#jiazushi button[data-target="#addJzsCase"]').removeClass('disabled');
                    $('#jiazushi button[data-target="#addJzsCase"]').removeAttr('disabled');
                }
            }
        });
    });//追加的家族史删除按钮 end
    //家族史  追加模板  start
    function jzsTemplet(num, jzsName) {
        var str = '<tr class="familyHistory jzs-' + num + '" data-type="extend"><td class="jzsTabel-title">家族史名称</td><td colspan="3" class="jzsCase-name"><label>' +
            '<input type="checkbox" name="jzs-' + num + '" checked disabled data-name="' + jzsName + '"> (亲属)患' + jzsName + '</label>' +
            '<button type="button" class="btn btn-outline btn-danger jzs-delete" data-tr="jzs-' + num + '">删除</button></td></tr>' +
            '<tr class="jzs-' + num + '"><td class="jzsTabel-title">直系亲属</td><td><label>' +
            '<input type="checkbox" data-type="lineal" data-num="' + num + '" name="father"/> 父</label><label>' +
            '<input type="checkbox" data-type="lineal" data-num="' + num + '" name="mother"/> 母</label><label>' +
            '<input type="checkbox" data-type="lineal" data-num="' + num + '" name="brother"/> 兄弟</label><label>' +
            '<input type="checkbox" data-type="lineal" data-num="' + num + '" name="sister"/> 姐妹</label><label>' +
            '<input type="checkbox" data-type="lineal" data-num="' + num + '" name="children"/> 子女</label></td><td class="jzsTabel-title">非直系亲属</td><td><label>' +
            '<input type="checkbox" data-type="notLineal" data-num="' + num + '" name="grandfather"/> 爷爷</label><label>' +
            '<input type="checkbox" data-type="notLineal" data-num="' + num + '" name="grandmother"/> 奶奶</label><label>' +
            '<input type="checkbox" data-type="notLineal" data-num="' + num + '" name="grandma"/> 姥姥</label><label>' +
            '<input type="checkbox" data-type="notLineal" data-num="' + num + '" name="grandpa"/> 姥爷</label><label>' +
            '<input type="checkbox" data-type="notLineal" data-num="' + num + '" name="uncle"/> 叔叔</label><label>' +
            '<input type="checkbox" data-type="notLineal" data-num="' + num + '" name="aunt"/> 姑姑</label><label>' +
            '<input type="checkbox" data-type="notLineal" data-num="' + num + '" name="wifeSister"/> 姨</label><label>' +
            '<input type="checkbox" data-type="notLineal" data-num="' + num + '" name="motherBrother"/> 舅舅</label><label>' +
            '<input type="checkbox" data-type="notLineal" data-num="' + num + '" name="other"/> 其他亲属</label></td></tr>';
        return str;
    }//家族史追加模板  end
    //家族史 添加家族史按钮 start
    $('#addJzs').click(function () {
        var jzsName = $('#addJzsCase .jzsName').val().trim();
        var jzs_list = $('#jzs_list');
        if (jzsName) {
            var trNum = (((jzs_list.find('tr')).length) / 2) - 5;
            if (trNum > 5) {
                alertModel('', '家族史可最多追加6组！');
            } else {
                jzs_list.append(jzsTemplet(trNum, jzsName));
                $('#addJzsCase .jzsName').val('');
                if (((((jzs_list.find('tr')).length) / 2) - 5) >= 6) {
                    var addJzsCaseBtn = $('#jiazushi button[data-target="#addJzsCase"]');
                    addJzsCaseBtn.addClass('disabled');
                    addJzsCaseBtn.attr('disabled', 'disabled');
                }
            }
        } else {
            alertModel('', '您未填写家族史名称，追加失败！');
        }
    });//添加家族史按钮 end
    //家族史  提交前整理数据  start
    function jzsGetData() {
        //家族史 需要提交的数据
        var jzsData = {  //家族史提交数据
            diabetes: {
                select: 0,
                lineal: {father: 0, mother: 0, brother: 0, sister: 0, children: 0},
                notLineal: {
                    grandfather: 0,
                    grandmother: 0,
                    grandma: 0,
                    grandpa: 0,
                    uncle: 0,
                    aunt: 0,
                    wifeSister: 0,
                    motherBrother: 0,
                    other: 0
                }
            },
            hypertension: {
                select: 0,
                lineal: {father: 0, mother: 0, brother: 0, sister: 0, children: 0},
                notLineal: {
                    grandfather: 0,
                    grandmother: 0,
                    grandma: 0,
                    grandpa: 0,
                    uncle: 0,
                    aunt: 0,
                    wifeSister: 0,
                    motherBrother: 0,
                    other: 0
                }
            },
            chd: {
                select: 0,
                lineal: {father: 0, mother: 0, brother: 0, sister: 0, children: 0},
                notLineal: {
                    grandfather: 0,
                    grandmother: 0,
                    grandma: 0,
                    grandpa: 0,
                    uncle: 0,
                    aunt: 0,
                    wifeSister: 0,
                    motherBrother: 0,
                    other: 0
                }
            },
            embolism: {
                select: 0,
                lineal: {father: 0, mother: 0, brother: 0, sister: 0, children: 0},
                notLineal: {
                    grandfather: 0,
                    grandmother: 0,
                    grandma: 0,
                    grandpa: 0,
                    uncle: 0,
                    aunt: 0,
                    wifeSister: 0,
                    motherBrother: 0,
                    other: 0
                }
            },
            hyperlipidemia: {
                select: 0,
                lineal: {father: 0, mother: 0, brother: 0, sister: 0, children: 0},
                notLineal: {
                    grandfather: 0,
                    grandmother: 0,
                    grandma: 0,
                    grandpa: 0,
                    uncle: 0,
                    aunt: 0,
                    wifeSister: 0,
                    motherBrother: 0,
                    other: 0
                }
            },
            tumor: {
                select: 0,
                lineal: {father: 0, mother: 0, brother: 0, sister: 0, children: 0},
                notLineal: {
                    grandfather: 0,
                    grandmother: 0,
                    grandma: 0,
                    grandpa: 0,
                    uncle: 0,
                    aunt: 0,
                    wifeSister: 0,
                    motherBrother: 0,
                    other: 0
                }
            },
            extend: ''
        };
        var nameTr = $('#jiazushi tr.familyHistory');
        for (var i = 0; i < nameTr.length; i++) {
            if ($(nameTr[i]).attr('data-type') == 'extend') {
                if (!jzsData.extend) {
                    jzsData.extend = [];
                }
                var extendFamilyType = $(nameTr[i]).next().find('td input');
                var extendEmpty = false;
                var extendObj = {};
                for (var q = 0; q < extendFamilyType.length; q++) {
                    if (!extendObj[($(extendFamilyType[q]).attr('data-type'))]) {
                        extendObj[($(extendFamilyType[q]).attr('data-type'))] = {};
                    }
                    if ($(extendFamilyType[q]).is(':checked')) {
                        extendEmpty = true;
                        extendObj[($(extendFamilyType[q]).attr('data-type'))][($(extendFamilyType[q]).attr('name'))] = 1;
                    } else {
                        extendObj[($(extendFamilyType[q]).attr('data-type'))][($(extendFamilyType[q]).attr('name'))] = 0;
                    }
                }
                if (extendEmpty) {
                    extendObj.name = $(nameTr[i]).find('input').attr('data-name');
                    jzsData.extend.push(extendObj);
                } else {
                    alertModel('', '请勾选' + $(nameTr[i]).find('input').attr('data-name') + '的亲属类型！');
                    return false;
                }
            } else {
                if ($(nameTr[i]).find('input').is(':checked')) {
                    var empty = false;
                    var key = $(nameTr[i]).find('input').attr('name');
                    var familyType = $(nameTr[i]).next().find('td input');
                    for (var j = 0; j < familyType.length; j++) {
                        if ($(familyType[j]).is(':checked')) {
                            empty = true;
                            jzsData[key][($(familyType[j]).attr('data-type'))][($(familyType[j]).attr('name'))] = 1;
                        }
                    }
                    if (empty) {
                        jzsData[key].select = 1;
                    } else {
                        alertModel('', '请勾选' + $(nameTr[i]).find('input').attr('data-name') + '的亲属类型！');
                        return false;
                    }
                }
            }
        }
        return jzsData;
    }

    //家族史  提交前整理数据  end
    //家族史  保存方法和点击事件  start
    function jzsSave(d,NEXT,activeID) {
        var jzsId = $('#jiazushi input.jzsId').val();
        var url = '/manage/family/store';
        if (jzsId) {
            url = '/manage/family/update';
        }
        if (record_id) {
            d.record_id = record_id;
        } else {
            alertModel('', '您还未创建病历，请先创建！');
            return;
        }
        d.remark = $('#jiazushi textarea').val();
        d.id = jzsId;
        ajaxPost(url, d, function (data) {
            if (data.code == 10000) {
                if (data.data && data.data.id) {
                    $('#jiazushi input.jzsId').val(data.data.id);
                    jzsId = data.data.id;
                }
                saveSeccessTab();
                if(NEXT=='NEXT'){
                    activeID.click()
                }else{
                    $.alert({
                        title: '温馨提示',
                        body: '保存成功！',
                        transition: true,
                        okHidden: function () {
                            // if (next) {
                            //     saveNext();  //跳转至下一页
                            // }
                        }
                    });
                }

            } else if (data.code === 40100) {
                aClick();
            } else {
                alertModel('', '保存失败！');
            }
        }, function (x, t, e) {
            if (x.status != 422) {
                alertModel('', '保存失败，再来一次吧！');
            }
        })
    }

    $('#jzsSave').click(function () {
        jzsSaveBtnClick();
    });
    function jzsSaveBtnClick(NEXT,activeID) {
        var data = jzsGetData();
        if (data) {
            jzsSave(data,NEXT,activeID);
        }
    }
    $('#jzsSaveNext').click(function () {
        saveNextFun($("#jzsSave"),$("a[href='#tigejiancha']"))
    });
    //家族史  保存方法和点击事件  end


    //主诉 添加一组症状按钮  start
    $('#addZsSymptom').click(function () {
        var ZsGroupDiv = $('#zs_symptom>div.row');
        for (var i = 0; i < ZsGroupDiv.length; i++) {
            var isHidden = $(ZsGroupDiv[i]).css('display');
            if (isHidden == 'none') {
                $(ZsGroupDiv[i]).show(300);
                checkNum(ZsGroupDiv, 'addZsSymptom', 5);
                break;
            }
        }
    });//主诉 添加一组症状按钮  end
    //主诉  症状组删除  start
    $('#zs_symptom').delegate('.delete-symptom', 'click', function () {
        var delZs = $(this).attr('data-id');
        confirmModel('温馨提示', '确认要删除吗？', '确定', '取消', function () {
            $('#' + delZs).hide(300);
            $('#' + delZs).find('ul.sui-tag').html('');
            $('#' + delZs).find('input').val('');
            if ($('#addZsSymptom').hasClass('disabled')) {
                $('#addZsSymptom').removeClass('disabled');
                $('#addZsSymptom').removeAttr('disabled');
            }
        });
    });//主诉  症状组删除  end
    //主诉 现病史  添加症状点击按钮  start
    $('.tab-content').delegate('.add-symptom', 'click', function () {
        var addSymptom_modal = $('#addSymptom .modal-body');  //弹出框的放置内容的父元素
        addSymptom_modal.html("");
        var addId = $(this).attr('data-id');  //获取点击的是那一组
        $('#saveSymptom').attr('data-id', addId);  //把症状组编码放入添加模态框保存按钮做记号
        var ulList = $('#' + addId).find('ul.sui-tag li');
        var selected = [];  //存放已选择的症状
        selectedSymptomList = selected;
        if (addId.indexOf("thyHB") >= 0) {
            ulList = $("button." + addId).parents("div.ibox").find('ul.sui-tag li');
        }

        for (var i = 0; i < ulList.length; i++) {
            selected.push({name: ($(ulList[i])).attr('data-name'), id: ($(ulList[i])).attr('data-id')});
        }
        if ((ulList.length) === 0) {  //判断改组症状是否已经选择了5个

            // if (MainSymptomsList.length == 0) {
            getMainSymptoms([], addId);
            // }
            // else {
            //     addSymptom_modal.html(MainSymptomsStr);
            // }
        } else if ((ulList.length) <= 5) {
            // if (MainSymptomsList.length == 0) {

            getMainSymptoms(selected, addId);
            // }
            // else {
            //     addSymptom_modal.html(MainSymptomsStr);
            //     for (var s = 0; s < selected.length; s++) {
            //         $('#addSymptom .modal-body').find('input[value="' + selected[s].name + '"]').parent().parent().addClass('current');
            //     }
            // }
        }
    });//主诉 现病史  添加症状点击按钮  end
    //主诉 现病史  页面上已经选择的症状删除 操作  start
    $('.tab-content').delegate('ul.sui-tag li', 'click', function () {
        var _this = $(this);
        confirmModel('温馨提示', '确认要删除吗？', '确定', '取消', function () {
            _this.remove();
        });
    });//主诉 现病史 页面上已经选择的症状删除 操作  end
    //主诉  体重变化选择改变事件  start
    $('.zsWeightChangeSelect').change(function () {
        var zsWeightChangeSize = $('.zsWeightChangeSize');
        if ($(this).val() == 0) {
            zsWeightChangeSize.hide(300);
            zsWeightChangeSize.find('input').val('');
        } else {
            zsWeightChangeSize.find(".zsWeightchangestatus option").eq(0).attr("selected", "selected").prop("selected", true).change();
            zsWeightChangeSize.find('input').val('');
            zsWeightChangeSize.show(300);
        }
    });//主诉  体重变化选择改变事件  end
    //主诉  提交前检测整理数据  start
    function checkData() {
        //主诉  需要提交的数据
        var zsData = {
            symptoms: [
                {
                    name: []
                },
                {
                    name: []
                },
                {
                    name: []
                },
                {
                    name: []
                },
                {
                    name: []
                }
            ],
            weightchange: 0,
            blood_glucose: {
                limosis: {
                    low: '',
                    high: ''
                },
                postprandial: {
                    low: '',
                    high: ''
                }
            },
            remark: '',
            record_id: '',
            id: ''
        };
        var complaintDiv = $('#zhusu #zs_symptom').find('div.row.border-bottom-dashed.padding-tb-15');
        var z = 0;
        for (var i = 0; i < complaintDiv.length; i++) {
            if ($(complaintDiv[i]).css('display') != 'none') {
                z++;
                var sDate = $(complaintDiv[i]).find('input.started_at').val();
                var eDate = $(complaintDiv[i]).find('input.exacerbated_at').val();
                if (sDate && eDate) {
                    if (checkTwoDate(sDate, eDate)) {
                        zsData.symptoms[i].started_at = sDate;
                        zsData.symptoms[i].exacerbated_at = eDate;
                    } else {
                        alertModel('', '症状组' + (z) + '的加重时间不能小于发病时间！');
                        return false;
                    }
                } else {
                    zsData.symptoms[i].started_at = sDate;
                    zsData.symptoms[i].exacerbated_at = eDate;
                }
                var symptomName = $(complaintDiv[i]).find('ul.sui-tag li');
                for (var s = 0; s < symptomName.length; s++) {
                    zsData.symptoms[i].name.push($(symptomName[s]).attr('data-name'));
                }
            }
        }

        zsData.weightchange = $('#zhusu #zsForm').find('.zsWeightChangeSelect').val();
        if (zsData.weightchange != 0) {
            zsData.weightchangestatus = $('#zhusu #zsForm').find('.zsWeightchangestatus').val();
            if (zsData.weightchangestatus == '1') {
                zsData.weightchangekg = $('#zhusu #zsForm').find('.weightchangekg').val();
            }
        }
        zsData.remark = $('#zhusu #zsForm').find('textarea').val();
        if (record_id) {
            zsData.record_id = record_id;
        } else {
            alertModel('', '您还未创建病历，请先创建！');
            return false;
        }
        var zsId = $('#zhusu input.zsId').val();//存储主诉id  第一次添加时为空  添加成功后更改值
        zsData.id = zsId;

        var bloodSugarInput = $('#zsForm .bloodSugar input');
        var bloodSugarArr = [];//存储四个血糖值
        for (var j = 0; j < bloodSugarInput.length; j++) {
            if ($(bloodSugarInput[j]).val()) {
                bloodSugarArr.push($(bloodSugarInput[j]).val());
            }
        }
        if (checkBloodNum(bloodSugarArr)) {
            zsData.blood_glucose.limosis.low = $('#zsForm .bloodSugar .limosis_low').val();
            zsData.blood_glucose.limosis.high = $('#zsForm .bloodSugar .limosis_high').val();
            zsData.blood_glucose.postprandial.low = $('#zsForm .bloodSugar .postprandial_low').val();
            zsData.blood_glucose.postprandial.high = $('#zsForm .bloodSugar .postprandial_high').val();
        } else {
            alertModel('', '请输入正确的血糖值！');
            return false;
        }

        // 川 ⤵️
        //获取用药史数据
        zsData['medication'] = '';
        // if ($('#jwsAddMedication1').html().trim()) {
        if ($('#zsAddMedication1').html().trim()) {
            zsData['medication'] = [];
            // var medicationTrList = $('#jwsAddMedication1 tbody tr');
            var medicationTrList = $('#zsAddMedication1 tbody tr');
            for (var y = 0; y < medicationTrList.length; y++) {
                var object = {};
                object['name'] = $(medicationTrList[y]).find('input.drugsid').val();
                object['start_time'] = $(medicationTrList[y]).find('input.drugsdate').val();
                object['end_time'] = $(medicationTrList[y]).find('input.drugsenddate').val();
                object['usage'] = $(medicationTrList[y]).find('input.usage').val();
                object['frequency'] = $(medicationTrList[y]).find('input.frequency').val();
                object['remark'] = $(medicationTrList[y]).find('input.remark').val();
                object['dosage'] = {};
                object['dosage']['unit'] = $(medicationTrList[y]).find('input.unit').val();
                if ($(medicationTrList[y]).find('input.dose').val()) {
                    object['dosage']['type'] = '每次剂量';
                    object['dosage']['value'] = $(medicationTrList[y]).find('input.dose').val();
                } else {
                    object['dosage']['type'] = '分次剂量';
                    object['dosage']['values'] = {};
                    object['dosage']['values']['morning'] = $(medicationTrList[y]).find('input.morning').val();
                    object['dosage']['values']['atnoon'] = $(medicationTrList[y]).find('input.atnoon').val();
                    object['dosage']['values']['evening'] = $(medicationTrList[y]).find('input.evening').val();
                    object['dosage']['values']['before_sleep'] = $(medicationTrList[y]).find('input.sleep').val();
                }
                zsData['medication'].push(object);
            }
        }
        for (var k = 1; k < zsData.symptoms.length; k++) {
            if (zsData.symptoms[k].name.length === 0 && ((zsData.symptoms[k].started_at === "") || zsData.symptoms === undefined) && ((zsData.symptoms[k].exacerbated_at === "") || zsData.symptoms === undefined)) {
                zsData.symptoms.splice(k--, 1);
            }
        }
        // 川⤴️
        return zsData;
    }//主诉  提交前检测整理数据  end


    //现病史  添加一组现病史按钮  start
    $('#addHpiGroup').click(function () {
        var ZsGroupDiv = $('#xbsGroupList>div');
        for (var i = 0; i < ZsGroupDiv.length; i++) {
            var isHidden = $(ZsGroupDiv[i]).css('display');
            if (isHidden == 'none') {
                $(ZsGroupDiv[i]).show(300);
                checkNum(ZsGroupDiv, 'addHpiGroup', 5);
                break;
            }
        }
    });//现病史  添加一组现病史按钮  end
    //现病史  追加的现病史组 删除按钮  start
    $('#xbsGroupList').delegate('.xbsAddGroupDelete', 'click', function () {
        var id = $(this).attr('data-group');
        var xbsGroupId = $('#' + id).find('input.xbsGroupId').val();
        confirmModel('温馨提示', '确认要删除吗？', '确定', '取消', function () {
            if (xbsGroupId) {
                xbsDeleteGroup(xbsGroupId, id);
            } else {
                $('#' + id).hide(300);
                $('#' + id).find('ul.sui-tag').html('');
                $('#' + id).find('div.hpiGroupTable').html('');
                $('#' + id).find('input').val('');
                $('#' + id).find('select').val('1');
            }
            if ($('#addHpiGroup').hasClass('disabled')) {
                $('#addHpiGroup').removeClass('disabled');
                $('#addHpiGroup').removeAttr('disabled');
            }
        });
    });

    function xbsDeleteGroup(xbsGroupId, id) {   //现病史  删除数据库
        $.post('/manage/hpiSub/destroy/' + xbsGroupId, {_method: 'DELETE'}, function (data) {
            if (data.code == 10000) {
                $('#' + id).hide(300);
                $('#' + id).find('ul.sui-tag').html('');
                $('#' + id).find('div.hpiGroupTable').html('');
                $('#' + id).find('input').val('');
                $('#' + id).find('select').val('1');
                alertModel('', '删除成功！');
            } else if (data.code === 40100) {
                aClick();
            } else {
                alertModel('', data.message);
            }
        });
    }

    //现病史  追加的现病史组 删除按钮  end
    //现病史  保存方法  start
    var modelBody = '', hpiSub = true;//存储现病史弹窗内容和现病史是否全部保存成功！
    function xbsSaveFun(url, result, idInputParent, idInput, pop, NEXT, activeID) {
        if (idInputParent != 'xianbingshi') {
            var hpiDivGroup = $('#' + idInputParent).parent().find('>div');
            var NUM = parseInt(idInputParent.substr(11, 1));
            var num = NUM + 1;
            for (var i = 0; i < NUM; i++) {
                if ($(hpiDivGroup[i]).css('display') != 'block') {
                    num--;
                }
            }
        }
        if (idInputParent != 'xianbingshi') {
            var xbsGroupId = $('#' + idInputParent + ' input.' + idInput).val();
        }
        ajaxPost(url, result, function (data) {
            if (data.code == 10000) {
                saveSeccessTab();
                if (data.data && data.data.id) {
                    $('#' + idInputParent + ' input.' + idInput).val(data.data.id);
                    if (idInput == 'xbsGroupId') {
                        if ($('#' + idInputParent + ' div.xbsGroupSaveBox').hasClass('display-none')) {
                            $('#' + idInputParent + ' div.xbsGroupSaveBox').removeClass('display-none');
                        }
                    }
                }
                if ((idInputParent == 'xianbingshi') && pop) {
                    modelBody += '一般情况保存成功！  ';
                    if (hpiSub) {
                        if (NEXT == 'NEXT') {
                            activeID.click();
                            scrollTo(0, 0)
                        } else {
                            $.alert({
                                title: '温馨提示',
                                body: '保存成功！',
                                transition: true,
                                okHidden: function () {
                                    modelBody = '';
                                    // if (next) {
                                    //     saveNext();  //跳转至下一页
                                    // }
                                }
                            });
                        }

                    }
                    else {
                        $.alert({
                            title: '温馨提示',
                            body: '现病史组保存失败，请重试！',
                            transition: true,
                            okHidden: function () {
                                // modelBody = '';
                                // if (next) {
                                //     saveNext();  //跳转至下一页
                                // }
                            }
                        });
                    }
                } else {
                    modelBody += '现病史组 ' + num + ' 保存成功！';
                }

                if (xbsGroupId) {
                    alertModel('', '现病史组 ' + num + ' 保存成功！');
                }
            } else if (data.code === 40100) {
                aClick();
            } else {
                if ((idInputParent == 'xianbingshi') && pop) {
                    modelBody += '一般情况保存失败  ';
                    $.alert({
                        title: '温馨提示',
                        body: '保存失败',
                        transition: true,
                        okHidden: function () {
                            modelBody = '';
                        }
                    });
                } else {
                    hpiSub = false;
                    modelBody += '现病史组 ' + num + ' 保存失败  ';
                }

                if (xbsGroupId) {
                    alertModel('', '现病史组 ' + num + ' 保存失败');
                }
            }
        }, function (x, t, e) {
            if (x.status != 422) {
                if ((idInputParent == 'xianbingshi') && pop) {
                    modelBody += '一般情况保存失败  ';
                    $.alert({
                        title: '温馨提示',
                        body: '保存失败',
                        transition: true,
                        okHidden: function () {
                            modelBody = '';
                        }
                    });
                } else {
                    hpiSub = false;
                    modelBody += '现病史组 ' + num + ' 保存失败  ';
                }

                if (xbsGroupId) {
                    alertModel('', '现病史组 ' + num + ' 保存失败');
                }
            }
        })
    } //现病史  保存方法  end
    //现病史  一般情况  提交前整理数据  start
    function xbsFinishingData() {
        var xbsData = {};//存储现病史数据
        xbsData.thyroid = {};//创建甲状腺对象
        xbsData.adrenal_gland = {};//创建高血压肾上腺对象
        xbsData.thyroid.symptoms = [];//甲状腺起病症状数组
        xbsData.thyroid.examination = [];//甲状腺化验检查数组
        xbsData.thyroid.hyperthyroidism = [];//甲状腺相关症状数组
        xbsData.adrenal_gland.symptoms = [];//高血压主要症状
        xbsData.adrenal_gland.accompanied_symptom = [];//高血压伴随症状
        // 获取一般情况数据  S
        var generalTdList = $('#xianbingshi .xbs-table td[data-name]');
        for (var i = 0; i < generalTdList.length; i++) {
            var tdKey = $(generalTdList[i]).attr('data-name');
            if (tdKey == 'sport') {
                xbsData[tdKey] = $(generalTdList[i]).find('.form-control').val();
            } else {
                xbsData[tdKey] = {};
                var generalTdDivList = $(generalTdList[i]).find('div[data-name]');
                for (var j = 0; j < generalTdDivList.length; j++) {
                    var tdDivKey = $(generalTdDivList[j]).attr('data-name');
                    var tdDivType = $(generalTdDivList[j]).attr('data-type');
                    if (tdDivType == 'obj') {
                        if (!xbsData[tdKey][tdDivKey]) {
                            xbsData[tdKey][tdDivKey] = {};
                        }
                        xbsData[tdKey][tdDivKey][$(generalTdDivList[j]).find('.form-control').attr('data-name')] = $(generalTdDivList[j]).find('.form-control').val();
                    } else {
                        if ($(generalTdDivList[j]).find('.form-control').attr('name')) {
                            var inputType = $(generalTdDivList[j]).find('.form-control').attr('type');
                            var val = $(generalTdDivList[j]).find('.form-control').val();
                            if (inputType == 'number') {
                                if (isNaN(val) || val < 0) {
                                    alertModel('', '请正确填写' + $(generalTdDivList[j]).find('span:first-child').html() + '的数量');
                                    return false;
                                } else {
                                    xbsData[tdKey][tdDivKey] = val;
                                }
                            } else {
                                xbsData[tdKey][tdDivKey] = val;
                            }
                        } else {
                            xbsData[tdKey][tdDivKey] = $(generalTdDivList[j]).find('input:checked').val();
                        }
                    }
                }
            }
        }
        // 获取一般情况数据  E
        xbsData['remark'] = $('#xianbingshi #xbsRemark').val();
        if (record_id) {
            xbsData['record_id'] = record_id;
        } else {
            alertModel('', '您还未创建病历，请先创建！');
            return false;
        }
        //甲状腺数据推入⬇️；
        var thyroid = $("#thyroidParent");
        var adrenal_gland = $("#adrenal_glandParent");

        xbsData.thyroid.started_at = thyroid.find("input.thyroidStarted_at").val();
        xbsData.thyroid.inducement = thyroid.find("select.thyroidInducement").val();
        xbsData.thyroid.symptoms_remark = thyroid.find("input.thyroid_symptoms_remark").val();
        xbsData.thyroid.examination_remark = thyroid.find("input.examination_remark").val();
        xbsData.thyroid.hyperthyroidism_remark = thyroid.find("input.hyperthyroidism_remark").val();
        $.each($(".thyroid li"), function (k, v) {
            xbsData.thyroid.symptoms.push($(v).attr("data-name"));
        });
        $.each($(".thyroid1 li"), function (k, v) {
            xbsData.thyroid.examination.push($(v).attr("data-name"));
        });
        $.each($(".thyroid2 li"), function (k, v) {
            xbsData.thyroid.hyperthyroidism.push($(v).attr("data-name"));
        });

        //高血压⬇️
        xbsData.adrenal_gland.started_at = adrenal_gland.find("input.started_at").val();
        xbsData.adrenal_gland.symptoms_remark = adrenal_gland.find("input.symptoms_remark").val();
        xbsData.adrenal_gland.accompanied_symptom_remark = adrenal_gland.find("input.accompanied_symptom_remark").val();
        $.each($(".highBlood li"), function (k, v) {
            xbsData.adrenal_gland.symptoms.push($(v).attr("data-name"));
        });
        $.each($(".highBlood1 li"), function (k, v) {
            xbsData.adrenal_gland.accompanied_symptom.push($(v).attr("data-name"));
        });

        // var thyroidInputs = $("#thyroidParnet").find("input,select");
        // $.each(thyroidInputs, function (i, v) {
        //     if($(v).val()!==""){
        //         if($(this).attr("name")=="symptom[]"){
        //             $(this).attr("name","thyroid[symptoms][]")
        //         }
        //         // xbsData[$(this).attr("name")]==$(this).val();
        //         console.log($(this).attr("name"));
        //
        //     }
        // });
        //高血压数据推入⬇️；
        return xbsData;
    } //现病史  一般情况  提交前整理数据  end
    //现病史 组  整理数据  start
    var generalSituation = true;//存储一般情况能否保存
    function xbsGroupData(id) {
        var hpiSub = {};
        //获取起病日期到症状数据
        var baseMessage = $('#' + id + ' div[data-name="hpiSub"] .updataBox');
        for (var i = 0; i < baseMessage.length; i++) {
            var key = $(baseMessage[i]).attr('data-name');
            var value = $(baseMessage[i]).find('.form-control').val();
            hpiSub[key] = value;
        }
        var symptomsInput = $('#' + id + ' .sui-tag input');
        hpiSub['symptoms'] = [];
        for (var j = 0; j < symptomsInput.length; j++) {
            hpiSub['symptoms'].push($(symptomsInput[j]).val());
        }
        if ((!hpiSub.started_at) || (!hpiSub.symptoms.length)) {
            alertModel('', '请填写现病史组的起病日期和起病症状！');
            return false;
        }
        //获取用药前和血糖后血糖值数据
        var bloodInput = $('#' + id + ' div.bloodInput');
        for (var s = 0; s < bloodInput.length; s++) {
            var bloodKey = $(bloodInput[s]).attr('data-name');
            hpiSub[bloodKey] = {};
            var bloodInputBox = $(bloodInput[s]).find('div[data-name]');
            for (var p = 0; p < bloodInputBox.length; p++) {
                var bloodInputBoxKey = $(bloodInputBox[p]).attr('data-name');
                if (bloodInputBoxKey == 'hba1c') {
                    var val = $(bloodInputBox[p]).find('.form-control').val();
                    if (val) {
                        if (isNaN(val) || val <= 0 || val > 99.9) {
                            alertModel('', '请正确填写HbA1c的值');
                            generalSituation = false;
                            return false;
                        } else {
                            hpiSub[bloodKey][bloodInputBoxKey] = val;
                        }
                    } else {
                        hpiSub[bloodKey][bloodInputBoxKey] = val;
                    }
                } else {
                    hpiSub[bloodKey][bloodInputBoxKey] = {};
                    var lowVal = $(bloodInputBox[p]).find('input[data-name="low"]').val();
                    var highVal = $(bloodInputBox[p]).find('input[data-name="high"]').val();
                    var bloodArr = [];
                    if (lowVal) {
                        bloodArr.push(lowVal)
                    }
                    if (highVal) {
                        bloodArr.push(highVal)
                    }
                    if (checkBloodNum(bloodArr)) {
                        hpiSub[bloodKey][bloodInputBoxKey]['low'] = lowVal;
                        hpiSub[bloodKey][bloodInputBoxKey]['high'] = highVal
                    } else {
                        alertModel('', '请正确填写血糖的值');
                        generalSituation = false;
                        return false;
                    }
                }
            }
        }
        //获取 汤药详情 的值  S
        if ($('#' + id + ' .hpiTcm').find('button.addTcmBtn').html()) {  //先判断是否有中医部分
            if ($('#' + id + ' .hpiTcm .xbsAddTcm').html().trim()) {
                hpiSub['cn_medication'] = [];
                var tcmTr = $('#' + id + ' .hpiTcm .xbsAddTcm tbody tr');
                if (tcmTr.length) {
                    for (var w = 0; w < tcmTr.length; w++) {
                        if ($(tcmTr[w]).attr("data-type") !== "3") {
                            var obj = {}, objDrugs = obj['drugs'] = [];
                            obj['usage'] = $(tcmTr[w]).find('input.takMethod').val();
                            obj['dosage'] = $(tcmTr[w]).find('input.frequency1').val();
                            obj['frequency'] = $(tcmTr[w]).find('input.frequency2').val();
                            obj['dose'] = $(tcmTr[w]).find('input.total').val();
                            obj['type'] = 1;
                            var tcmNameTds = $(tcmTr[w]).find('td:first-child input');
                            for (var p = 0; p < tcmNameTds.length; p++) {
                                objDrugs.push({
                                    'name': $(tcmNameTds[p]).val(),
                                    'weight': $(tcmNameTds[p]).attr('data-num')
                                });
                            }
                            hpiSub['cn_medication'].push(obj);
                        } else {
                            // todo 此处添加
                            var obj = {};
                            obj['name'] = $(tcmTr[w]).find('input.tableSelectTcm').val();//药名
                            obj['start_time'] = $(tcmTr[w]).find('input.stime').val();//开始时间
                            obj['end_time'] = $(tcmTr[w]).find('input.etime').val();//结束时间
                            obj['times_per_day'] = $(tcmTr[w]).find('input.times').val();//每一次数
                            obj['quantity_per_times'] = $(tcmTr[w]).find('input.numMe').val();//每次数量
                            obj['quantity_unit'] = $(tcmTr[w]).find('input.unit').val();//单位
                            obj['total'] = $(tcmTr[w]).find('input.boxNum').val();//总数
                            obj['type'] = 3;//总数

                            hpiSub['cn_medication'].push(obj);
                        }

                    }
                }
            } else {
                hpiSub['cn_medication'] = '';
            }
        }
        //获取 汤药详情 的值  E
        //获取 诊断 的值  S
        var diagnoseInput = $('#' + id + ' div.xbsAddDiagnosis input[type="hidden"]');
        hpiSub['diagnose'] = [];
        if (diagnoseInput.length) {
            for (var z = 0; z < diagnoseInput.length; z++) {
                if (hpiSub['diagnose'].indexOf($(diagnoseInput[z]).val()) == -1) {
                    hpiSub['diagnose'].push($(diagnoseInput[z]).val());
                }
            }
        } else {
            hpiSub.diagnose = '';
        }
        //获取 诊断 的值  E
        //获取 用药 的值  S
        hpiSub['medication'] = '';
        if ($('#' + id + ' div.xbsAddMedication').html().trim()) {
            hpiSub['medication'] = [];
            var medicationTrList = $('#' + id + ' div.xbsAddMedication tbody tr');
            for (var y = 0; y < medicationTrList.length; y++) {
                var object = {};
                object['name'] = $(medicationTrList[y]).find('input.drugsid').val();
                object['start_time'] = $(medicationTrList[y]).find('input.drugsdate').val();
                object['end_time'] = $(medicationTrList[y]).find('input.drugsenddate').val();
                object['usage'] = $(medicationTrList[y]).find('input.usage').val();
                object['frequency'] = $(medicationTrList[y]).find('input.frequency').val();
                object['remark'] = $(medicationTrList[y]).find('input.remark').val();
                object['dosage'] = {};
                object['dosage']['unit'] = $(medicationTrList[y]).find('input.unit').val();
                if ($(medicationTrList[y]).find('input.dose').val()) {
                    object['dosage']['type'] = '每次剂量';
                    object['dosage']['value'] = $(medicationTrList[y]).find('input.dose').val();
                } else {
                    object['dosage']['type'] = '分次剂量';
                    object['dosage']['values'] = {};
                    object['dosage']['values']['morning'] = $(medicationTrList[y]).find('input.morning').val();
                    object['dosage']['values']['atnoon'] = $(medicationTrList[y]).find('input.atnoon').val();
                    object['dosage']['values']['evening'] = $(medicationTrList[y]).find('input.evening').val();
                    object['dosage']['values']['before_sleep'] = $(medicationTrList[y]).find('input.sleep').val();
                }
                hpiSub['medication'].push(object);
            }
        }
        //获取 用药 的值  E
        if (record_id) {
            hpiSub['record_id'] = record_id;
        } else {
            alertModel('', '您还未创建病历，请先创建！');
            return false;
        }
        generalSituation = true;

        return hpiSub;
    }

    //现病史 组  整理数据  end
    //现病史  保存按钮  start
    $('#xianbingshi #xbsSave').click(function (next) {
        xbsSaveBtnClick();//封装的保存交互事件
    });

    function xbsSaveBtnClick(NEXT, activeID) {
        if ((isXbsGroupSave()) && generalSituation) {
            var data = xbsFinishingData();
            if (data) {
                var xbsId = $('#xianbingshi input.xbsId').val();
                var url = '/manage/hpi/store';
                if (xbsId) {
                    url = '/manage/hpi/update';
                }
                data['id'] = xbsId;
                xbsSaveFun(url, data, 'xianbingshi', 'xbsId', 'pop', NEXT, activeID);
            }
        }
    }

    //现病史保存并下一步重写⬇️

    // $('#xianbingshi #xbsSaveNext').click(function () {
    //     if ((isXbsGroupSave()) && generalSituation) {
    //         var data = xbsFinishingData();
    //         if (data) {
    //             var xbsId = $('#xianbingshi input.xbsId').val();
    //             var url = '/manage/hpi/store';
    //             if (xbsId) {
    //                 url = '/manage/hpi/update';
    //             }
    //             data['id'] = xbsId;
    //             xbsSaveFun(url, data, 'xianbingshi', 'xbsId', 'pop', 'next');
    //         }
    //     }
    // });
    $('#xianbingshi #xbsSaveNext').click(function () {
        saveNextFun($("#xbsSave"), $("a[href='#jiwangshi']"))
    });


    $('#xbsGroupList button.xbsGroupSave').click(function () {
        var id = $(this).attr('data-id');
        if (xbsGroupData(id)) {
            var xbsGroupId = $('#' + id + ' input.xbsGroupId').val();
            var url = '/manage/hpiSub/store';
            if (xbsGroupId) {
                url = '/manage/hpiSub/update';
            }
            var data = xbsGroupData(id);
            data['id'] = xbsGroupId;
            xbsSaveFun(url, data, id, 'xbsGroupId');
        }
    });
    //现病史  保存按钮  end
    //现病史保存时 查看是否要对现病史组保存  start
    function isXbsGroupSave() {
        var groupDiv = $('#xianbingshi #xbsGroupList>div');
        for (var i = 0; i < groupDiv.length; i++) {
            if ($(groupDiv[i]).css('display') == 'block') {
                var time = $(groupDiv[i]).find('div[data-name="started_at"] input').val();
                var symptom = $(groupDiv[i]).find('ul.sui-tag').html().trim();
                var id = $(groupDiv[i]).find('input.xbsGroupId').val();
                if (time && symptom) {
                    if (!id) {
                        $(groupDiv[i]).find('button.xbsGroupSave').click();
                    }
                } else {
                    alertModel('', '请填写现病史组的起病日期和起病症状！');
                    return false;
                    break;
                }
            }
        }
        return true;
    }

    //现病史保存时 查看是否要对现病史组保存  end

    //现病史  监测血糖  start
    $('#monitoringBlood').click(function () {
        if (record_id) {
            window.open("http://www.365tang.cn/datacenter/firstdetail?id=" + record_id);
        } else {
            alertModel('', '您还未创建病历，请先创建！');
        }
    });
    //现病史  监测血糖  end


    //个人史  吸烟饮酒事件变化  start
    $('.grsDateInput').blur(function () {
        var _this = $(this);
        setTimeout(function () {
            var select = $('#' + _this.attr('data-id'));
            if (_this.val()) {
                select.show(300);
            } else {
                select.hide(300);
                select.find('input').val('');
            }
        }, 300);
    }); //个人史  吸烟饮酒事件变化  end
    //个人史 数据保存方法 和保存按钮点击  start
    function grsSaveFun(NEXT,activeID) {
        var grsId = $('#gerenshi input.gerId').val();
        var result = $('#gerenshi form').serialize();
        if (record_id) {
            result += '&id=' + grsId + '&record_id=' + record_id;
        } else {
            alertModel('', '您还未创建病历，请先创建！');
            return;
        }
        var smokeTime = $('#gerenshi').find('input[data-id="smokeTime"]').val();
        var stop_smoke = $('#gerenshi').find('input[name="stop_smoke"]').val();
        var drinkTime = $('#gerenshi').find('input[data-id="drinkTime"]').val();
        var stop_drink = $('#gerenshi').find('input[name="stop_drink"]').val();
        if (smokeTime && stop_smoke) {
            if (!checkTwoDate(smokeTime, stop_smoke)) {
                alertModel('', '吸烟时间或戒烟时间选择不正确！');
                return;
            }
        }
        if (drinkTime && stop_drink) {
            if (!checkTwoDate(drinkTime, stop_drink)) {
                alertModel('', '喝酒时间或戒酒时间选择不正确！');
                return;
            }
        }
        //判断四个时间  不能大于出生时间
        var birthday = $('#birthday').val();
        if (smokeTime) {
            if (!checkTwoDate(birthday, smokeTime)) {
                alertModel('', '出生时间不能晚于吸烟时间！');
                return;
            }
        }
        if (stop_smoke) {
            if (!checkTwoDate(birthday, stop_smoke)) {
                alertModel('', '出生时间不能晚于戒烟时间！');
                return;
            }
        }
        if (drinkTime) {
            if (!checkTwoDate(birthday, drinkTime)) {
                alertModel('', '出生时间不能晚于喝酒时间！');
                return;
            }
        }
        if (stop_drink) {
            if (!checkTwoDate(birthday, stop_drink)) {
                alertModel('', '出生时间不能晚于戒酒时间！');
                return;
            }
        }
        var NumberInput = [$('#gerenshi').find('.many').val(), $('#gerenshi').find('.whiteSpirit').val(), $('#gerenshi').find('.redSpirit').val(), $('#gerenshi').find('.beer').val()];
        if (checkIsNumber(NumberInput)) {
            var url = '/manage/person/store';
            if (grsId) {
                url = '/manage/person/update';
            }
            ajaxPost(url, result, function (data) {
                if (data.code == 10000) {
                    if (data.data && data.data.id) {
                        $('#gerenshi input.gerId').val(data.data.id);
                        grsId = data.data.id;
                    }
                    saveSeccessTab();
                    if(NEXT=="NEXT"){
                        activeID.click();
                        scrollTo(0,0);
                    }else{
                        $.alert({
                            title: '温馨提示',
                            body: '保存成功！',
                            transition: true,
                            okHidden: function () {
                                // if (next) {
                                //     saveNext();  //跳转至下一页
                                // }
                            }
                        });
                    }

                } else if (data.code === 40100) {
                    aClick();
                } else {
                    alertModel('', '保存失败！');
                }
            }, function (x, t, e) {
                if (x.status != 422) {
                    alertModel('', '保存失败，再来一次吧！');
                }
            })
        } else {
            alertModel('', '请输入正确的数量词！');
        }
    }

    $('#grsSave').click(function () {
        grsSaveBtnClick();
    });
    function grsSaveBtnClick(NEXT,activeID) {
        grsSaveFun(NEXT,activeID);
    }
    $('#grsSaveNext').click(function () {
        saveNextFun($("#grsSave"),$("a[href='#hunyushi']"))
    });//个人史 数据保存方法 和保存按钮点击  end


    //既往史  支架置入时间  添加按钮  start
    $('#jiwangshi').delegate('button.stentsPlacementTimeBtn', 'click', function () {
        $('#addStentsTime #addStentsTimeBtn').attr('data-id', $(this).attr('data-id'));
    });//既往史  支架置入时间  添加按钮  end
    //既往史 支架置入时间弹出框  添加按钮  start
    $('#addStentsTime #addStentsTimeBtn').click(function () {
        var val = $('#addStentsTime input.datepicker').val();
        if (val) {
            var id = $(this).attr('data-id');
            if ($('#' + id).html().trim() != '') {
                if (($('#' + id).find('tbody tr').length) < 10) {
                    var str = '<tr><td>' + val + '<input type="hidden" name="stentsDate[]" value="' + val + '"></td><td><button type="button" class="btn btn-outline btn-danger stentsTimeDelete">删除</button></td></tr>';
                    $('#' + id).find('tbody').append(str);
                }
                else {
                    $.alert({
                        title: '温馨提示',
                        body: '支架最多可添加10组！',
                        transition: true,
                        okHidden: function () {
                            $('.sui-modal-backdrop.fade.in').removeClass('alertZindex');
                        }
                    });
                    $('.sui-modal-backdrop.fade.in').addClass('alertZindex');
                }
            } else {
                var allStr = '<table class="table-bordered table-striped table-hover text-center stentsTime-table"><thead><tr><th>置入时间</th><th>操作</th></tr></thead><tbody><tr><td>' + val + '<input type="hidden" name="stentsDate[]" value="' + val + '"></td><td><button type="button" class="btn btn-outline btn-danger stentsTimeDelete">删除</button></td></tr></tbody></table>';
                $('#' + id).html(allStr);
            }
            $('#addStentsTime button.closeAddStentsTime').click();
            $('#addStentsTime input').val('');
        } else {
            $.alert({
                title: '温馨提示',
                body: '请选择置入日期！',
                transition: true,
                okHidden: function () {
                    $('.sui-modal-backdrop.fade.in').removeClass('alertZindex');
                }
            });
            $('.sui-modal-backdrop.fade.in').addClass('alertZindex');
        }
    });//既往史 支架置入时间弹出框  添加按钮  end
    //既往史 支架置入时间  删除按钮  start
    $('#jiwangshi').delegate('.stentsTimeDelete', 'click', function () {
        var _this = $(this);
        confirmModel('', '', '', '', function () {
            var tbody = _this.parent().parent().parent();
            if (tbody.find('tr').length == 1) {
                _this.parent().parent().parent().parent().remove();
            } else {
                _this.parent().parent().remove();
            }
        });
    });//既往史 支架置入时间  删除按钮  end
    //既往史  添加手术 和编辑手术 删除手术  start
    var jwsModelAddSurgeryBtn = $('#addSurgery #addSurgeryBtn');
    $('#jiwangshi').delegate('button.jwsAddSurgeryBtn', 'click', function () {
        jwsModelAddSurgeryBtn.attr('data-id', $(this).attr('data-id'));
        jwsModelAddSurgeryBtn.attr('data-edit', '');
        jwsModelAddSurgeryBtn.html('添加');
    });
    $('#jiwangshi').delegate('button.jwsEditSurgeryBtn', 'click', function () {
        jwsModelAddSurgeryBtn.html('修改');
        $('#addSurgery').find('input.datepicker').val($(this).parent().parent().find('input.surgery-date').val());
        $('#addSurgery').find('input.surgeryName').val($(this).parent().parent().find('input.surgery-name').val());
        jwsModelAddSurgeryBtn.attr('data-edit', $(this).attr('data-edit'));
        jwsModelAddSurgeryBtn.attr('data-id', $(this).attr('data-id'));

    });
    $('#jiwangshi').delegate('button.surgeryDelete', 'click', function () {
        var _this = $(this);
        confirmModel('', '', '', '', function () {
            var tbody = _this.parent().parent().parent();
            if (tbody.find('tr').length == 1) {
                _this.parent().parent().parent().parent().remove();
            } else {
                _this.parent().parent().remove();
            }
        });
    });//既往史  添加手术 和编辑手术 删除手术  end
    //既往史  添加手术弹出框添加按钮  start
    jwsModelAddSurgeryBtn.click(function () {
        var id = $(this).attr('data-id');
        var trClass = $(this).attr('data-edit');
        var surgery_date = $('#addSurgery').find('input.datepicker').val();
        var surgery_name = $('#addSurgery').find('input.surgeryName').val();
        if (!surgery_date) {
            $.alert({
                title: '温馨提示',
                body: '请选择手术日期！',
                transition: true,
                okHidden: function () {
                    $('.sui-modal-backdrop.fade.in').removeClass('alertZindex');
                }
            });
            $('.sui-modal-backdrop.fade.in').addClass('alertZindex');
        }
        else {
            if (!surgery_name) {
                $.alert({
                    title: '温馨提示',
                    body: '请填写手术名称！',
                    transition: true,
                    okHidden: function () {
                        $('.sui-modal-backdrop.fade.in').removeClass('alertZindex');
                    }
                });
                $('.sui-modal-backdrop.fade.in').addClass('alertZindex');
            } else {
                if (trClass) {  //先判断是添加还是编辑  有trClass是编辑   此处为编辑
                    $('#' + id + ' tr.' + trClass).find('td:first-child').html(surgery_date + '<input type="hidden" class="surgery-date" value="' + surgery_date + '" name="surgeryDate[]">');
                    $('#' + id + ' tr.' + trClass).find('td:first-child+td').html(surgery_name + '<input type="hidden" class="surgery-name" value="' + surgery_name + '" name="surgeryDate[]">');
                } else {   //此处添加添加
                    var addBox = $('#' + id);
                    if (addBox.html().trim() == '') {
                        var allStr = '<table class="table-bordered table-striped table-hover text-center medicationList-table"><thead><tr><th>手术日期</th><th>手术名称</th><th>操作</th></tr></thead><tbody>' +
                            '<tr class="surgery1"><td>' + surgery_date + '<input type="hidden" class="surgery-date" value="' + surgery_date + '" name="surgeryDate[]"></td>' +
                            '<td>' + surgery_name + '<input type="hidden" class="surgery-name" value="' + surgery_name + '" name="surgeryDate[]"></td><td>' +
                            '<button type="button" class="btn btn-outline btn-primary margin-right-5 jwsEditSurgeryBtn" data-toggle="modal" data-target="#addSurgery" data-edit="surgery1" data-id="jwsAddSurgery">编辑</button>' +
                            '<button type="button" class="btn btn-outline btn-danger surgeryDelete">删除</button></td></tr></tbody></table>';
                        addBox.html(allStr);
                    } else {
                        var trNum = (addBox.find('tbody tr').length) + 1;
                        var str = '<tr class="surgery' + trNum + '"><td>' + surgery_date + '<input type="hidden" class="surgery-date" value="' + surgery_date + '" name="surgeryDate[]"></td>' +
                            '<td>' + surgery_name + '<input type="hidden" class="surgery-name" value="' + surgery_name + '" name="surgeryDate[]"></td><td>' +
                            '<button type="button" class="btn btn-outline btn-primary margin-right-5 jwsEditSurgeryBtn" data-toggle="modal" data-target="#addSurgery" data-edit="surgery' + trNum + '" data-id="jwsAddSurgery">编辑</button>' +
                            '<button type="button" class="btn btn-outline btn-danger surgeryDelete">删除</button></td></tr>';
                        addBox.find('tbody').append(str);
                    }
                }
                $('#addSurgery button.closeAddSurgery').click();
                $('#addSurgery input').val('');
            }
        }
    });//既往史  添加手术弹出框添加按钮  end
    //初始化之前添加了几组病史；
    var dataNum = 0;
    if ($("#jiwangshi table.medicalHistory-table tbody").find("tr").last().find('td').last().attr("data-name").indexOf("newAdd") >= 0) {
        dataNum = Number($("#jiwangshi table.medicalHistory-table tbody").find("tr").last().find('td').last().attr("data-name").slice('newAdd'))
    }
    // 添加一组病史点击确定添加⬇️
    $("#addJws").click(function () {
        if ($("#jiwangshi table.medicalHistory-table tbody").find("tr").last().find('td').first().attr("data-id") >= 0) {
            dataNum = Number($("#jiwangshi table.medicalHistory-table tbody").find("tr").last().find('td').first().attr("data-id"))
        }
        // console.log($("#addJwsCase").find("input[name='jwsName']").val());
        var html = '';
        var val = $("#addJwsCase").find("input[name='jwsName']").val();
        var tbody = $("#jiwangshi table.medicalHistory-table>tbody");
        if (val !== "") {
            dataNum++;
            html = '<tr><td data-id="' + dataNum + '" data-name="extra[' + dataNum + ']" class="inputList bg-default removeTd">' + val + '<input type="hidden" class="form-control input-text" data-name="name" value="' + val + '" name="name"> <br></td>' +
                '<td data-id="' + dataNum + '" class="inputList removeTd" data-name="extra[' + dataNum + ']">' +
                '<div class="medicalHistory-box">' +
                '<span class="input-title">时间</span>' +
                '<input type="text" data-name="time" name="jws_newDate" class="form-control input-text maxMonth" placeholder="请选择时间" data-toggle="datepicker">' +
                '</div>' +
                '<div class="medicalHistory-box  margin-top-10">' +
                '<span class="input-title">备注</span>' +
                '<input type="text" data-name="remark" name="remark" class="form-control input-text" maxlength="50" placeholder="请添加备注">' +
                '</div>' +
                '</td>' +
                '<td data-id="' + dataNum + '" class="drugList removeTd" data-name="extra[' + dataNum + ']">' +
                '<div id="newAddDrug' + dataNum + '">' +
                '<ul class="sui-tag">' +
                '</ul>' +
                '</div>' +
                '<button type="button" class="btn btn-outline btn-primary selectDrugBtn" data-toggle="modal" data-target="#selectDrugs" data-id="newAddDrug' + dataNum + '">选择药物' +
                '</button>' +
                '</td><td><button style="margin-top: 10px;" data-id="' + dataNum + '" class="btn btn-outline btn-danger addDelete">删除</button>' +
                '</td>' +
                '</tr>';
            tbody.append(html);
            dateInit();//日期初始化
            $("#addJwsCase").find("input[name='jwsName']").val("");
        } else {
            $.alert({
                title: '温馨提示',
                body: '病史名称不能为空'
            });
        }

        // dataNum++;
    });
    $("#jiwangshi").delegate(".addDelete", "click", function () {
        var that = this;
        $(this).parents("tr").remove();
        // setTimeout(function(){
        //     if($(this).attr("data-id")%2!==0){
        //         $.each($(".removeTd"),function(k,v){
        //                 if($(this).attr("data-id")%2==0){
        //                     if(Number($(v).attr('data-id'))>=Number($(this).attr("data-id"))){
        //                         console.log($(v).attr("data-id"));
        //                     $(v).parent("tr").prev("tr").append($(v));
        //                 }
        //             }
        //
        //         });
        //
        //     }else{
        //         console.log(2)
        //     }
        // },200);


        // $.each($("td.removeTd"), function (z, x) {
        //     if (Number($(x).attr('data-id')) > Number($(that).attr("data-id"))) {
        //         var num=Number(($(x).attr('data-id')) - 1);
        //         $(x).attr('data-id', num);
        //         $(x).attr('data-name', 'extra[' +num + ']');
        //         // $(x).attr('data-name', 'extra[' +num + ']');
        //
        //     }
        // });
        // dataNum--

    });


    //新添加的日期进行初始化
    function dateInit() {
        var date = new Date();

        function formatDate(date) {
            var y = date.getFullYear();
            var m = date.getMonth() + 1;
            m = m < 10 ? '0' + m : m;
            var d = date.getDate();
            d = d < 10 ? ('0' + d) : d;
            return y + '-' + m + '-' + d;
        };
        $('.maxMonth').datepicker({
            minViewMode: 1,
            format: 'yyyy-mm',
            endDate: formatDate(date)
        });//日历最多显示到月  end

    };

    //既往史胰腺炎史  急性慢性只能选择一个控制  start
    $('.pancreatitisInput').blur(function () {
        var _this = $(this);
        setTimeout(function () {
            if (_this.val()) {
                _this.parent().siblings().find('input').val('');
            }
        }, 300);
    });
    //既往史胰腺炎史  急性慢性只能选择一个控制  end
    //既往史  选择药物按钮  点击事件  start
    var jwsPageSelectedDrug = [];//存储选择药物点击按钮对应的已经存在的药物的列表名称  选择药物弹出框添加药物或去除药物均操作该数组
    var drupParam = {  //请求药物时候需要的参数
        type: 2,
        name: '',
        group: '',
        size: 100,
        page: 1
    };
    var jwsModelSelectDrugsBtn = $('#selectDrugs #addSelectDrugsBtn');
    $('#jiwangshi').delegate('button.selectDrugBtn', 'click', function () {
        jwsPageSelectedDrug = [];
        var id = $(this).attr('data-id');
        jwsModelSelectDrugsBtn.attr('data-id', id);
        var inputArr = $('#' + id).find('ul.sui-tag li input');
        for (var i = 0; i < inputArr.length; i++) {
            jwsPageSelectedDrug.push($(inputArr[i]).val());
        }
        if ($('#selectDrugs .selectDrugs-search select').html().trim() == '') {  //如果选择药物弹窗框  药品列表  为空（没请求过）
            drugGroup();
        }
        drugList(drupParam);
        // changeSelectModelDrug();
    });//既往史  选择药物按钮  点击事件  end
    //如果页面有已经选择药物  将弹出框所对应药物标注为选中状态方法  start
    function changeSelectModelDrug() {
        if (jwsPageSelectedDrug) {  //判断页面上有已经选择
            for (var i = 0; i < jwsPageSelectedDrug.length; i++) {
                var select = $('#selectDrugs .drugListBox').find('label[data-name="' + jwsPageSelectedDrug[i] + '"]');
                if (select) {
                    if (!(select.parent().hasClass('current'))) {
                        select.parent().addClass('current');
                    }
                }
            }
        }
    }//如果页面有已经选择药物  将弹出框所对应药物标注为选中状态方法  end
    //选择药物弹出框  获取药品种类列表方法  start
    function drugGroup() {
        $.get('/manage/drug/group', function (data) {
            if (data.code == 10000) {
                var str = '<option value="">全部</option>';
                $.each(data.data, function (i, v) {
                    str += '<option value="' + v.key + '">' + v.value + '</option>';
                });
                $('#selectDrugs .selectDrugs-search select').html(str);
            } else if (data.code === 40100) {
                aClick();
            } else {
                alertModel('', data.message)
            }
        })
    }//选择药物弹出框  获取药品种类列表方法  end
    //选择药物弹出框  获取药物列表方法  start
    function drugList(d) {
        $.get('/manage/drug/list', d, function (data) {
            if (data.code == 10000) {
                if (data.data.length > 0) {
                    var str = '<div class="addModel-group">';
                    $.each(data.data, function (i, v) {
                        str += '<div class="lable-item"><label data-name="' + v.name + '">' + v.name + '</label></div>';
                    });
                    str += '</div>';
                    $('#selectDrugs div.drugListBox').html(str);
                    changeSelectModelDrug();  //将页面上已经有的  添加样式
                }
                else {
                    $('#selectDrugs div.drugListBox').html('<div class="text-center addModel-group"><h5>暂无数据</h5></div>');
                    drupParam.name = '';
                    drupParam.group = '';
                    $('#selectDrugs input.diagnosisName').val('');
                    $('#selectDrugs select.diagnosisType').val('');
                }
                // 页码
                if (data.meta.pagination.total_pages > 1) {
                    page('selectDrugsPage', data.meta, drugList, drupParam);
                } else {
                    $('#selectDrugsPage').html('');
                }
            } else if (data.code === 40100) {
                aClick();
            } else {
                $('#selectDrugs div.drugListBox').html('<div class="text-center addModel-group"><h5>暂无数据</h5></div>');
                drupParam.name = '';
                drupParam.group = '';
                $('#selectDrugs input.diagnosisName').val('');
                $('#selectDrugs select.diagnosisType').val('');
                $('#selectDrugsPage').html('');
            }
        })
    } //选择药物弹出框  获取药物列表方法  end
    //选择药物弹出框  药物点击事件  start
    $('#selectDrugs div.drugListBox').delegate('div.lable-item label', 'click', function () {
        if ($(this).parent().hasClass('current')) {
            $(this).parent().removeClass('current');
            for (var i = 0; i < jwsPageSelectedDrug.length; i++) {
                if ($(this).attr('data-name') == jwsPageSelectedDrug[i]) {
                    jwsPageSelectedDrug.splice(i, 1);
                }
            }
        } else {
            $(this).parent().addClass('current');
            jwsPageSelectedDrug.push($(this).attr('data-name'));
        }
    }); //选择药物弹出框  药物点击事件  end
    //选择药物弹出框  添加按钮  start
    $('#selectDrugs #addSelectDrugsBtn').click(function () {
        var id = $(this).attr('data-id');
        var str = '';
        for (var i = 0; i < jwsPageSelectedDrug.length; i++) {
            str += '<li class="tag-selected with-x"><input type="hidden" value="' + jwsPageSelectedDrug[i] + '" name="symptom[]">' + jwsPageSelectedDrug[i] + '<i>×</i></li>';
        }
        $('#' + id).find('ul.sui-tag').html(str);
        $('#selectDrugs button.closeSelectDrugsBtn').click();
        $('#selectDrugs input.diagnosisName').val('');
        $('#selectDrugs select.diagnosisType').val('');
        jwsPageSelectedDrug = [];
        drupParam.page = 1;
        drupParam.name = '';
        drupParam.group = '';
    });//选择药物弹出框  添加按钮  end
    //选择药物弹出框  搜索功能   start
    $('#selectDrugs button.selectDrugsSearch').click(function () {
        drupParam.name = $(this).parent().find('.diagnosisName').val();
        drupParam.group = $(this).parent().find('.diagnosisType').val();
        drupParam.page = 1;
        if (drupParam.group == '') {
            // if (drupParam.name == '') {
            //     $.alert({
            //         title: '温馨提示',
            //         body: '搜索全部请输入关键字！',
            //         transition: true,
            //         okHidden: function () {
            //             $('.sui-modal-backdrop.fade.in').removeClass('alertZindex');
            //         }
            //     });
            //     $('.sui-modal-backdrop.fade.in').addClass('alertZindex');
            // } else {
            drugList(drupParam);
            // }
        } else {
            drugList(drupParam);
        }
    }); //选择药物弹出框  搜索功能   end

    var jwsUpdata = {};//保存既往史所提交的数据
    //既往史  提交前获取并整理数据  start
    function jwsData() {
        //判断肥胖的两个时间
        var startTime = $('#jiwangshi td[data-name="fat"] .startTime').val();
        var endTime = $('#jiwangshi td[data-name="fat"] .endTime').val();
        if (startTime && endTime) {
            if (!checkTwoDate(startTime, endTime)) {
                alertModel('', '肥胖的结束时间不能大于开始时间');
                return false;
            }
        }
        //验证数字
        var maskInput = $('input.maskNum');
        for (var k = 0; k < maskInput.length; k++) {
            var val = $(maskInput[k]).val();
            if (val) {
                if (isNaN(val) || val < 0) {
                    alertModel('', $(maskInput[k]).attr('data-title') + '输入不正确！');
                    return false;
                }
            }
        }
        //获取药物数据
        var drugsList = $('#jiwangshi .medicalHistory-table td.drugList');
        for (var i = 0; i < drugsList.length; i++) {
            var key = $(drugsList[i]).attr('data-name');
            var drugsInput = $(drugsList[i]).find('input');
            if (!(jwsUpdata[key])) {
                jwsUpdata[key] = {};
            }
            jwsUpdata[key]['drugs'] = '';
            if (drugsInput.length > 0) {
                jwsUpdata[key]['drugs'] = [];
                for (var j = 0; j < drugsInput.length; j++) {
                    jwsUpdata[key]['drugs'].push($(drugsInput[j]).val());
                }
            }
        }
        //获取输入框数据
        var inputList = $('#jiwangshi .medicalHistory-table td.inputList');
        for (var s = 0; s < inputList.length; s++) {
            var inputKey = $(inputList[s]).attr('data-name');
            var inputVal = $(inputList[s]).find('input');
            for (var z = 0; z < inputVal.length; z++) {
                var inputName = $(inputVal[z]).attr('data-name');
                var val = $(inputVal[z]).val();
                // if(val){
                if (!(jwsUpdata[inputKey])) {
                    jwsUpdata[inputKey] = {};
                }
                jwsUpdata[inputKey][inputName] = val;
                // }
            }
            var selectVal = $(inputList[s]).find('select');
            for (var x = 0; x < selectVal.length; x++) {
                var selectName = $(selectVal[x]).attr('data-name');
                var selectedVal = $(selectVal[x]).val();
                if (!(jwsUpdata[inputKey])) {
                    jwsUpdata[inputKey] = {};
                }
                jwsUpdata[inputKey][selectName] = selectedVal;
            }
        }

        // chuan   获取名字数据⬇️

        //获取冠心病史数据
        var coronary_disease = $('#jiwangshi .medicalHistory-table div.coronary_disease');
        for (var q = 0; q < coronary_disease.length; q++) {
            var valName = $(coronary_disease[q]).find('input').attr('data-name');
            var inpVal = $(coronary_disease[q]).find('input').val();
            if (inpVal) {
                if (!(jwsUpdata['coronary_disease'])) {
                    jwsUpdata['coronary_disease'] = {};
                }
                jwsUpdata['coronary_disease'][valName] = inpVal;
            }
        }
        var tableInput = $('#jiwangshi .medicalHistory-table .coronary_disease_table').find('input');
        if (!(jwsUpdata['coronary_disease'])) {
            jwsUpdata['coronary_disease'] = {};
        }
        jwsUpdata['coronary_disease']['stenting'] = '';
        if (tableInput.length > 0) {
            jwsUpdata['coronary_disease']['stenting'] = [];
            for (var e = 0; e < tableInput.length; e++) {
                jwsUpdata['coronary_disease']['stenting'].push($(tableInput[e]).val());
            }
        }

        // 手术史用钥匙暂时注释⬇️2018.3.21
        //获取手术史数据
        // jwsUpdata['operation'] = '';
        // if ($('#jwsAddSurgery').html().trim()) {
        //     jwsUpdata['operation'] = [];
        //     var trList = $('#jwsAddSurgery tbody tr');
        //     for (var t = 0; t < trList.length; t++) {
        //         var obj = {};
        //         obj['time'] = $(trList[t]).find('input.surgery-date').val();
        //         obj['name'] = $(trList[t]).find('input.surgery-name').val();
        //         jwsUpdata['operation'].push(obj);
        //     }
        // }
        // //获取用药史数据
        // jwsUpdata['medication'] = '';
        // if ($('#jwsAddMedication').html().trim()) {
        //     jwsUpdata['medication'] = [];
        //     var medicationTrList = $('#jwsAddMedication tbody tr');
        //     for (var y = 0; y < medicationTrList.length; y++) {
        //         var object = {};
        //         object['name'] = $(medicationTrList[y]).find('input.drugsid').val();
        //         object['start_time'] = $(medicationTrList[y]).find('input.drugsdate').val();
        //         object['end_time'] = $(medicationTrList[y]).find('input.drugsenddate').val();
        //         object['usage'] = $(medicationTrList[y]).find('input.usage').val();
        //         object['frequency'] = $(medicationTrList[y]).find('input.frequency').val();
        //         object['remark'] = $(medicationTrList[y]).find('input.remark').val();
        //         object['dosage'] = {};
        //         object['dosage']['unit'] = $(medicationTrList[y]).find('input.unit').val();
        //         if ($(medicationTrList[y]).find('input.dose').val()) {
        //             object['dosage']['type'] = '每次剂量';
        //             object['dosage']['value'] = $(medicationTrList[y]).find('input.dose').val();
        //         } else {
        //             object['dosage']['type'] = '分次剂量';
        //             object['dosage']['values'] = {};
        //             object['dosage']['values']['morning'] = $(medicationTrList[y]).find('input.morning').val();
        //             object['dosage']['values']['atnoon'] = $(medicationTrList[y]).find('input.atnoon').val();
        //             object['dosage']['values']['evening'] = $(medicationTrList[y]).find('input.evening').val();
        //             object['dosage']['values']['before_sleep'] = $(medicationTrList[y]).find('input.sleep').val();
        //         }
        //         jwsUpdata['medication'].push(object);
        //     }
        // }
        //提交数据中加入  病历ID  备注信息
        jwsUpdata['remark'] = $('#jiwangshi div.margin-top-20 textarea').val();
        if (record_id) {
            jwsUpdata['record_id'] = record_id;
        } else {
            alertModel('', '您还未创建病历，请先创建！');
            return false;
        }
        return true;
    }//既往史  提交前获取并整理数据  end
    //既往史  提交数据方法  start
    function jwsUpdataFun(NEXT, activeID) {
        var jwsId = $('#jiwangshi input.jwsId').val();
        jwsUpdata['id'] = jwsId;
        var url = '/manage/past/store';
        if (jwsId) {
            url = '/manage/past/update';
        }
        // console.log(jwsUpdata);
        ajaxPost(url, jwsUpdata, function (data) {
            if (data.code == 10000) {
                if (data.data && data.data.id) {
                    $('#jiwangshi input.jwsId').val(data.data.id);
                }
                saveSeccessTab();
                if(NEXT=="NEXT"){
                    activeID.click();
                    scrollTo(0,0);
                }else{
                    $.alert({
                        title: '温馨提示',
                        body: '保存成功！',
                        transition: true,
                        okHidden: function () {
                            // if (next) {
                            //     saveNext();  //跳转至下一页
                            // }
                        }
                    });
                }

            } else if (data.code === 40100) {
                aClick();
            } else {
                alertModel('', '保存失败！');
            }
        }, function (x, t, e) {
            if (x.status != 422) {
                alertModel('', '保存失败，再来一次吧！');
            }
        })
    } //既往史  提交数据方法  end
    //既往史  保存按钮  start
    $('#jwsSave').click(function () {
        jwsSaveBtnClick()
    });

    function jwsSaveBtnClick(NEXT, activeID) {
        if (jwsData()) {
            jwsUpdataFun(NEXT, activeID);
        }
    }

    //既往史保存下一步重写⬇️

    // $('#jwsSaveNext').click(function () {
    //     if (jwsData()) {
    //         jwsUpdataFun('next');
    //     }
    // });
    $('#jwsSaveNext').click(function () {
        saveNextFun($("#jwsSave"), $("a[href='#gerenshi']"))
    });
    //既往史  保存按钮  end


    //月经婚育史  检测数值大雨0  start
    function hysCheckNum() {
        var inputMask = $('#hunyushi form.hysForm input.numberMask');
        var inputValArr = [];
        for (var i = 0; i < inputMask.length; i++) {
            var val = $(inputMask[i]).val();
            if (val) {
                inputValArr.push(val);
            }
        }
        if (inputValArr.length) {
            if (checkIsNumber(inputValArr)) {
                return true;
            } else {
                alertModel('', '请输入正确的数字！');
                return false;
            }
        } else {
            return true;
        }
    };//月经婚育史  检测数值大雨0  end
    //月经婚育史  数据保存方法   start
    function hysSaveData(NEXT,activeID) {
        var hysId = $('#hunyushi input.hysId').val();
        var result = $('#hunyushi form.hysForm').serialize();
        if (record_id) {
            result += '&id=' + hysId + '&record_id=' + record_id;
        } else {
            alertModel('', '您还未创建病历，请先创建！');
            return;
        }
        var url = '/manage/marriage/store';
        if (hysId) {
            url = '/manage/marriage/update';
        }
        ajaxPost(url, result, function (data) {
            if (data.code == 10000) {
                if (data.data && data.data.id) {
                    $('#hunyushi input.hysId').val(data.data.id);
                    hysId = data.data.id;
                }
                saveSeccessTab();
                if(NEXT=='NEXT'){
                    activeID.click();
                    scrollTo(0,0);
                }else{
                    $.alert({
                        title: '温馨提示',
                        body: '保存成功！',
                        transition: true,
                        okHidden: function () {
                            // if (next) {
                            //     saveNext();  //跳转至下一页
                            // }

                        }
                    });
                }

            } else if (data.code === 40100) {
                aClick();
            } else {
                alertModel('', '保存失败！');
            }
        }, function (x, t, e) {
            if (x.status != 422) {
                alertModel('', '保存失败，再来一次吧！');
            }
        })
    }//月经婚育史  数据保存方法   end
    //月经婚育史   保存按钮点击事件   start
    $('#hunyushi #hysSave').click(function () {
        hysSaveBtnClick()
    });
    function hysSaveBtnClick(NEXT,activeID) {
        if (hysCheckNum()) {
            hysSaveData(NEXT,activeID);
        }
    }
    $('#hunyushi #hysSaveNext').click(function () {
        saveNextFun($("#hysSave"),$("a[href='#jiazushi']"))
    });//月经婚育史   保存按钮点击事件   end

    //检查返回数据是否是undefined
    function checkUndefined(data) {
        return (data === undefined || data === null) ? "" : data;

    };

    //当用户点击保存并下一步时，先调用保存，放返回保存成功！（true）时，调用li的tab a的点击事件⬇️
    //
    function saveNextFun(saveID, activeID) {
        var selfFun = $(saveID)[0].id + 'BtnClick';
        eval(selfFun)('NEXT', activeID);
    }

    //主诉  保存方法 和点击事件  start
    function zsSaveFun(d, NEXT, activeID) {
        var zsId = $('#zhusu input.zsId').val();//存储主诉id  第一次添加时为空  添加成功后更改值
        var url = '/manage/complaint/store';
        if (zsId) {
            url = '/manage/complaint/update';
        }
        ajaxPost(url, d, function (data) {
            if (data.code == 10000) {
                if (data.data && data.data.id) {
                    $('#zhusu input.zsId').val(data.data.id);
                }
                saveSeccessTab();
                if (NEXT == "NEXT") {
                    activeID.click();
                    scrollTo(0, 0)
                } else {
                    $.alert({
                        title: '温馨提示',
                        body: '保存成功！',
                        transition: true,
                        okHidden: function () {
                            // if (next) {
                            //     saveNext();  //跳转至下一页
                            // }

                        }
                    });
                }

            } else if (data.code === 40100) {
                aClick();
            } else {
                alertModel('', '保存失败！');
            }
        }, function (x, t, e) {
            if (x.status != 422) {
                alertModel('', '保存失败，再来一次吧！');
            }
        });
    }

    $('#zsSave').click(function (next) {
        zsSaveBtnClick();
    });

    function zsSaveBtnClick(NEXT, activeID) {
        var d = checkData();
        if (d) {
            zsSaveFun(d, NEXT, activeID);
        }
    }

    // ⬇️ 主诉保存并下一步重写⬇️️

    // $('#zsSaveNext').click(function () {
    //     var d = checkData();
    //     if (d) {
    //         zsSaveFun(d, 'next');
    //     }
    // });
    $('#zsSaveNext').click(function () {
        saveNextFun($('#zsSave'), $('li[data-href=hpi]').find('a'));
    });
    //主诉  保存方法 和点击事件  end

});

